Skip to content
Advertisement

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?

JavaScript

Desired result:

JavaScript

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:

JavaScript

Advertisement

Answer

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

JavaScript

Output of this example is :

JavaScript

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement