-1

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?

Jamie Moffat
  • 127
  • 1
  • 13

1 Answers1

3

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];
}
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • I'd suggest building it as a function so you can use it in multiple places if needed. – Allen Butler Oct 06 '16 at 15:24
  • If the keys are always sequential in both arrays you can replace the first two lines with `foreach($vars as $i => $value) {` – Steve Oct 06 '16 at 15:54