merging two arrays with specified index



PHP Snippet 1:

function foo(array $p, array $q): array {
    $r = [array_shift($p)];

    foreach ($q as $x) {
        $r[] = $x;
        $r[] = array_shift($p);
    }

    return $r;
}

print_r(
    foo([210,11,12], ['-', '/'])
);

print_r(
    foo([210,11,12,12], ['-','/','/'])
);

PHP Snippet 2:

function foo(array $p, array $q): array {
    $r = [$p[0]];

    foreach ($q as $i => $x) {
        $r[] = $x;
        $r[] = $p[$i + 1];
    }

    return $r;
}

PHP Snippet 3:

$arr3 = array_merge(...array_map(null, $arr1, $arr2));
array_pop($arr3);

PHP Snippet 4:

[[210, '/'], [11, '/'], [12, '/'], [12, null]]

PHP Snippet 5:

echo implode(' ', array_merge(...array_map(null, $arr1, $arr2)));

PHP Snippet 6:

$arr1 = [210,11,12,12];
$arr2 = ['-','/','/'];

foreach($arr1 as $key => $val){
    $arr3[] = $val;
    if(isset($arr2[$key])) $arr3[] = $arr2[$key];
}
var_dump($arr3);
//[210, -, 11, /, 12, /, 12]

PHP Snippet 7:

$numbers = [210, 11, 12];
$operators = ['-', '/'];

$result = (array)($numbers[0] ?? []);
foreach ($operators as $i => $operator) {
    array_push($result, $operator, $numbers[++$i]);
}
var_export($result);

PHP Snippet 8:

var_export(
    array_reduce(
        $operators,
        function($result, $operator) use($numbers) {
            static $i = 0;
            array_push($result, $operator, $numbers[++$i]);
            return $result;
        },
        (array)($numbers[0] ?? [])
    )
);