3

How can I merge two arrays when array 1 values 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);
Ben
  • 25,389
  • 34
  • 109
  • 165

4 Answers4

5

This will work correctly no matter the length of the two arrays, or their keys (it does not index into them):

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

Edit: My original answer had a bug; fixed that.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • this solution is perfect, not only merge two array, it works with nth array to combine as a one by one key merge from all array – Harsh Patel Oct 28 '21 at 06:10
3

try this

$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);

returns

Array
(
    [0] => 11
    [1] => 12
    [2] => 34
    [3] => 666
    [4] => 30
    [5] => 23
    [6] => 35
)
xkeshav
  • 53,360
  • 44
  • 177
  • 245
2

Assuming $arr1 and $arr2 are simple enumerated arrays of equal size, or where $arr2 has only one element less that $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];
    }
}
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • 1
    This won't work if the second array is longer, or if the arrays are not numerically indexed. – Jon Mar 07 '11 at 11:38
  • @Jon - I think the first line of my answer actually says that... the bit about "Assuming $arr1 and $arr2 are simple enumerated arrays of equal size, or where $arr2 has only one element less that $arr1" – Mark Baker Mar 07 '11 at 11:40
1

Go through array with more items, use loop index to access both arrays and combine them into resulting one as required...

$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
   }
}
rdamborsky
  • 1,920
  • 1
  • 16
  • 21