phparraysloopsarray-mergearray-splice

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


What would be an elegant way to merge two arrays, such that the resulting array has two items from the first array followed by a single item from the second array, repeating in this fashion?

$array1 = ['A1', 'A2', 'A3', 'A4', 'A5']; // potentially longer
$array2 = ['B1', 'B2', 'B3', 'B4', 'B5']; // potentially longer

Desired result:

['A1', 'A2', 'B1', 'A3', 'A4', 'B2', 'A5', 'B3', 'B4', 'B5']

I'm trying to do it using a for loop with multiple counters, but I don't know that the array lengths will be. I'm curious: is there a better way?

Here's a simplified version of what I'm currently doing:

$x = 0, $y = 0;
for ($i = 0; $i < $total_num_blocks; $i++) {
    if ($i % 3) {   // if there's a remainder, it's not an 'every 3rd' item
        $result[$i] = $projects[$x++];
    } else {
        $result[$i] = $posts[$y++];
    }
}

Solution

  • 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.