PHP :: How are merge 2 arrays when the values ​​of array 1 will be in even places and array 2 will be in odd places?

How can I combine two arrays when the values ​​of array 1 will be in even places and array 2 will be in odd places?

Example:

$arr1=array(11, 34,30);
$arr2=array(12, 666);
$output=array(11, 12, 34, 666,30);
+3
source share
4 answers

This will work correctly regardless of the length of two arrays or their keys (they are not indexed in them):

$result = array();
while(!empty($arr1) || !empty($arr2)) {
    if(!empty($arr1)) {
        $result[] = array_shift($arr1);
    }
    if(!empty($arr2)) {
        $result[] = array_shift($arr2);
    }
}

Change . My original answer had a mistake; fixed it.

+3
source

Assuming $ arr1 and $ arr2 are the simple listed arrays of the same size, or where $ arr2 has only one element less than $ arr1.

$arr1 = array(11, 34); 
$arr2 = array(12, 666);
$output = array();
foreach($arr1 as $key => $value) {
    $output[] = $value;
    if (isset($arr2[$key])) {
        $output[] = $arr2[$key];
    }
}
+2
source

$arr1=array(11,34,30,35);
$arr2=array(12,666,23);

$odd= array_combine(range(0,2*count($arr1)-1,2), $arr1);
$even = array_combine(range(1,2*count($arr2)-1,2), $arr2);
$output=$odd+$even;
ksort($output);
echo "<pre>";
print_r($output);

Array
(
    [0] => 11
    [1] => 12
    [2] => 34
    [3] => 666
    [4] => 30
    [5] => 23
    [6] => 35
)
+2

, ...

$longer = (count($arr1) > count($arr2) ? $arr1 : $arr2);
$result = array();
for ($i = 0; $i < count($longer); $i++) {
   $result[] = $arr1[i];
   if ($arr2[i]) {
      $result[] = $arr2[i];
   } else {
      $result[] = 0; // no item in arr2 for given index
   }
}
+1

All Articles