First is a solution that will consume the input arrays in a loop while building the new structure. You can always cache separate copies of the input if you need them elsewhere.
All solutions below will work even if the two arrays have different lengths -- any remaining elements will be appended to the end of the result array after the loop.
Code: (Demo)
$result = [];
while ($arr1 && $arr2) {
$result += array_splice($arr1, 0, 1)
+ array_splice($arr2, 0, 1);
}
$result += $arr1 + $arr2;
var_export($result);
Another way without consuming the input arrays is to build lookup arrays:
Code: (Demo)
$max = max(count($arr1), count($arr2));
$keys1 = array_keys($arr1);
$keys2 = array_keys($arr2);
$result = [];
for ($x = 0; $x < $max; ++$x) {
if (isset($keys1[$x])) {
$result[$keys1[$x]] = $arr1[$keys1[$x]];
}
if (isset($keys2[$x])) {
$result[$keys2[$x]] = $arr2[$keys2[$x]];
}
}
var_export($result);
Or you could use array_slice()
to isolate one element at a time from each array without damaging the input arrays, nor generating warnings.
Code: (Demo)
$result = [];
for ($i = 0, $count = count($arr1); $i < $count; ++$i) {
$result += array_slice($arr1, $i, 1)
+ array_slice($arr2, $i, 1);
}
$result += $arr1 + $arr2;