0

I have two arrays like

$first = 
Array
(
  [0] => 1
  [1] => 2
  [2] => 3
  [3] => 4
  [4] => 5
  [5] => 6
)

$second = 

Array
(
  [0] => apples
  [1] => organges
  [2] => bananas
  [3] => peaches
)

But, I want to push the second array elements into the first array by index. like

$result = 
Array
(
  [0] => 1
  [1] => apples
  [2] => 2
  [3] => organges
  [4] => 3
  [5] => 4
  [6] => peaches
  [7] => 5
  [8] => 6
)

without changing the first elements order.help me please

1 Answers1

1

You can, make a simple loop:

$result = [];
for($i=0; $i < count($first); $i++) {
    if(isset($first[$i])){$result[] = $first[$i];}
    if(isset($second[$i])){$result[] = $second[$i];}
}

If your array have variable size, compare their size first and do the loop with the bigger count.

EDIT:

Then taking in account you want to conserve their respective order, but merge randomly the arrays you could twist the previous code that way:

$result = [];
for($i=0; $i < count($first); $i++) {
    if(rand(0,1)) {
        if(isset($first[$i])){$result[] = $first[$i];}
        if(isset($second[$i])){$result[] = $second[$i];}
    } else {
        if(isset($second[$i])){$result[] = $second[$i];}
        if(isset($first[$i])){$result[] = $first[$i];}
    }
}

I admit it's very weird and twisted and I'm sure something more optimized could be made (it's done quickly), but, the question itself is weird xD I hope it will help :)

EDIT 2:

In fact the first edit will only alternate A/B, for a full random solution and still respecting the respective order of both arrays:

$result = [];
$end=count($first) + count($second);
$a=0;
$b=0;
for($i=0; $i < $end; $i++ {
    if(rand(0,1)) {
        if(isset($first[$a])) {
            $result[] = $first[$a];
            $a++;
        } elseif (isset($second[$b])) {
            $result[] = $second[$b];
            $b++;
        }
    } else {
        if(isset($second[$b])) {
            $result[] = $second[$b];
            $b++;
        } elseif (isset($first[$a])) {
            $result[] = $first[$a];
            $a++;
        }
    }
}
WizardNx
  • 697
  • 5
  • 10