Search code examples
phparraysarray-merge

PHP::How merge 2 arrays when array 1 values will be in even places and array 2 will be in odd places?


How can I merge two arrays when array 1 values will be in even places and array 2 will be in odd places?

Example:

$arr1=array(11, 34,30);
$arr2=array(12, 666);
$output=array(11, 12, 34, 666,30);

Solution

  • This will work correctly no matter the length of the two arrays, or their keys (it does not index into them):

    $result = array();
    while(!empty($arr1) || !empty($arr2)) {
        if(!empty($arr1)) {
            $result[] = array_shift($arr1);
        }
        if(!empty($arr2)) {
            $result[] = array_shift($arr2);
        }
    }
    

    Edit: My original answer had a bug; fixed that.