h4k1m h4k1m - 6 months ago 41
PHP Question

Merge two arrays alternatively

What I want is an

efficient
(without looping) way to merge arrays in the way that the
first element of the resulting array
is the
first element of the first array
,
the second element of the resulting array
is
the second element of the second array
(alternatively)... etc

Example:

$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);

$resultingArray = array(1, 2, 3, 4, 5, 6);

Answer

assuming both arrays have the same length.

$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);

$new = array();
for ($i=0; $i<count($arr1); $i++) {
   $new[] = $arr1[$i];
   $new[] = $arr2[$i];
}
var_dump($new);
Comments