# php - 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++];
}
}
```

## Answer

## Solution:

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

Output of this example is :

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.## Answer

## Solution:

Note: This is destructive of $posts and $projects.

## Answer

## Solution:

Results with

Instead of keeping track of the second array, you can reverse the second array, and array_pop it. http://php.net/manual/en/function.array-pop.php

array_pop() pops and returns the last value of the array, shortening the array by one element. If array is empty (or is not an array), NULL will be returned. Will additionally produce a Warning when called on a non-array.

You may want to finish off the Resultant array by adding all remaining items from array2 to the end of your resultant array.

## Answer

## Solution:

I don't know if it is elegant or efficient, you have to run some benchmark by yourself, but there is a fun way to merge those arrays without loops:

## Answer

## Solution:

I've extended @GlaviÄ‡'s excellent, excellent looped array injection script to provide greater control of the frequency of insertion and the amount of data per insertion.

This script is designed to work with non-negative parameters. The input arrays may be of any length with no requirement to share the same length. The first array is modified to become the result array, so if you need to preserve its initial data, you'll need to save a copy before iterating.

Have a play by modifying the arrays,

`$afterEvery`

, and`$insertCount`

in the 3v4l.org demo link.Code: (Demo)

Cases with arithmetic breakdown: