Insert elements from one array (one-at-a-time) after every second element of another array (un-even zippering)

This example will work regardless of the $a and $b array size.

<?php 

$a = ['A1', 'A2', 'A3', 'A4', 'A5'];
$b = ['BB1', 'BB2', 'BB3', 'BB4', 'BB5'];

for ($i = 0; $i < count($b); $i++) {
    array_splice($a, ($i+1)*2+$i, 0, $b[$i]);
}

echo "<pre>" . print_r($a, true) . "</pre>";

Output of this example is :

Array
(
    [0] => A1
    [1] => A2
    [2] => BB1
    [3] => A3
    [4] => A4
    [5] => BB2
    [6] => A5
    [7] => BB3
    [8] => BB4
    [9] => BB5
)

Warning: keys are NOT preserved!

This is PHP 5.4.x code, if you don’t have it, replace [] with array() in $a and $b variables.

Leave a Comment