phparraysmergealternating

Merge two flat indexed arrays of equal size so that values are pushed into the result in an alternating fashion


Suppose I have two arrays:

$a1 = array(0, 1, 2);
$a2 = array(3, 4, 5);

I want to be able to do a merge technique that alternates the array values and not just concatenate them. I want this result:

array(0, 3, 1, 4, 2, 5);

Is there a native way to do this as performance is an issue here since I need to do this thousands of times

Please note, I know I can do it like this:

for (var $i = 0; $i < count($a1); $i++) {
    newArray[] = $a1[$i];
    newArray[] = $b1[$i];
}

I'm looking for a built in way if there is a faster one.


Solution

  • $count = count($a1);
    for ($i = 0; $i < $count; $i++) {
        $newArray[] = $a1[$i];
        $newArray[] = $b1[$i];
    }
    

    My work here is done.

    $a1 = array(0,1,2);
    $a2 = array(3,4,5);
    
    $start = microtime(TRUE);
    
    for($t = 0; $t < 100000; $t++)
    {
        $newArray = array();
        $count = count($a1);
        for ($i = 0; $i < $count; $i++)
        {
            $newArray[] = $a1[$i];
            $newArray[] = $a2[$i];
        }
    }
    echo  round(microtime(TRUE) - $start, 2); # 0.6
    
    $a1 = array(0,1,2);
    $a2 = array(3,4,5);
    
    $start = microtime(TRUE);
    
    for($t = 0; $t < 100000; $t++)
    {
        $newArray = array();
        for ($i = 0; $i < count($a1); $i++)
        {
            $newArray[] = $a1[$i];
            $newArray[] = $a2[$i];
        }
    }
    echo  round(microtime(TRUE) - $start, 2); # 0.85
    

    So pre-counting array size will be ~1/4 [citation needed] (on freakin' 100.000 iterations you will gain 0.2 in total) faster. If you put count() inside loop, it will recount on every iteration. 1/4 seems to me a reasonably faster. If you are looking for compiled function, you can stop.

    P.S. Benchmark is like bikini, it shows you everything, and nothing.