Andrey Vorobyev
Andrey Vorobyev

Reputation: 886

Merge two flat arrays in an alternating fashion

I have 2 arrays

$arr1 = array(1, 3);  
$arr2 = array(2, 4);  

I want merge them to one array with structure:

$arr = array(1, 2, 3, 4);  

Are there PHP functions for that or does there exist a good solution?

I don't need sort values; I want to put elements from first array to odd positions, elements from second to even positions.

Upvotes: 0

Views: 123

Answers (3)

Kasapo
Kasapo

Reputation: 5374

No. Php does not have a function for this that I know of. You'll have to write your own, but it's very simple.

Pseudocode:

cmb = []

for (i=0, i<arr1.length, i++) {
   array_push(cmb, arr1[i]);
   array_push(cmb, arr2[i]);
}

Upvotes: 0

Paolo Bergantino
Paolo Bergantino

Reputation: 488394

You would have to merge them first, then sort them:

$arr = array_merge($arr1, $arr2);
sort($arr);

There is no built-in function to do what you are describing, assuming they are both the same length:

$len = count($arr1);
for($x=0; $x < $len; $x++) {
    array_push($arr, $arr1[$x], $arr2[$x]);
}

Upvotes: 8

tigertrussell
tigertrussell

Reputation: 521

$new_arr = array_merge($arr1, $arr2)

Upvotes: 0

Related Questions