phparraysmerging-dataalternating

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.


Solution

  • 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]);
    }