Jamie Moffat Jamie Moffat - 3 months ago 44
PHP Question

Merge array values, alternating

I'm trying to merge arrays but would like to alternate the order.

$combined = array_merge($vars,$mods);

gives me: one,two,three,1,2,3...

I'd like: one,1,two,2,three,3...

is there a way to do this?


You can use a for loop and refer to the index of each of the arrays you're combining.

$l = count($vars);
for ($i=0; $i < $l; $i++) {
    $combined[] = $vars[$i];
    $combined[] = $mods[$i];

In each iteration of the loop, you'll append one item from each of the original arrays. This will achieve the alternating effect.

As Steve pointed out, this can be done more simply using foreach:

foreach ($vars as $i => $value) {
    $combined[] = $value;
    $combined[] = $mods[$i];