Question

Suppose, that I have 3 arrays:

$a = [ 1, 2, 3 ];       // victim #1
$b = [ 4, 5, 6, 7, 8];  // victim #2
$result = [];           // result

I need to merge $a and $b in such order, that each element of $a array should be followed by element of array $b. Elements of $b array, however, might follow each other.

For example:

1 4 2 5 6 3 7 8

I have tried this:

while($a || $b)
    {
        $bool = rand(1, 100) >= 50;

        if($a)
            {
                $result[] = array_shift($a);
            }

        if($b)
            {
                $result[] = array_shift($b);
            }

        if($bool && $b)
            {
                $result[] = array_shift($b);
            }
    }

Which gives desired output:

Array
(
    [0] => 1
    [1] => 4
    [2] => 5
    [3] => 2
    [4] => 6
    [5] => 7
    [6] => 3
    [7] => 8
)

However, I think that it might be inefficient because of array_shift()s and if()s appears too much times there.

Question: Is there more efficient way to do that?

P.S.: Thanks, but I do really know how to use array_merge(). It is not the RTM issue.

Was it helpful?

Solution

foreach ($a as $value) {
    $result[] = $value;
    do {
        $bool = rand(0,1) == 1;
        $result[] = array_shift($b);
    } while ($bool);
}
// insert the remaining of value $b in the $result
foreach ($b as $value)
    $result[] = $value;

OTHER TIPS

$a = array(1, 2, 3 );       // victim #1
$b = array( 4, 5, 6, 7, 8);  // victim #2


foreach($a as $first)
{
   $result[] = $first;
}

foreach($b as $second)
{
   $result[] = $second;
}

Alternatively

$a = array(1, 2, 3, 9 );       // victim #1
$b = array( 4, 5, 6, 7, 8);  // victim #2
$result = array_merge($a,$b);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top