-1

What is the best possible way to merge two given array as shown below

$a = [1, 2, 3];
$b = [a, b, c];


$results = [1, a, 2, b, 3, c];
user4676307
  • 409
  • 8
  • 22

3 Answers3

2

A simple loop might well be the simplest way

$a = [1, 2, 3];
$b = [a, b, c];
$results = [];

foreach ($a as $key => $val) {
    $results[] = $val;
    // just in case the 2 arrays are not the same length
    if ( isset($b[$key] ){
        $results[] = $b[$key];
    }
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

As I've understood your question you want to merge these two arrays alternatively?

$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);
$count = (count($arr1) <= count($arr2)) ? count($arr2) : count($arr1);
$new = array();
for ($i = 0; $i < $count; $i++) 
{
    if(array_key_exists($arr1[$i])
    {
        $new[] = $arr1[$i];
    }
    if(array_key_exists($arr2[$i])
    {
        $new[] = $arr2[$i];
    }
}

So it will merge it alternatively and for error-prevention it checks if key exists.

spyro95
  • 136
  • 9
-1

Check this

<?php
    $a = [1, 2, 3];
    $b = [a, b, c];

    $cntA = count($a);
    $cntB = count($b);

    $results = [];
    $count = ($cntA <= $cntB) ? $cntB : $cntA;

    for($i=0; $i < count; $i++)
    {
        if($cntA >= $i) $results[] = $a[$i];
        if($cntB >= $i) $results[] = $b[$i];
    }
treyBake
  • 6,440
  • 6
  • 26
  • 57
  • 2
    code-only answers aren't answers IMO and should have explanations so OP and future readers can learn – treyBake Jul 17 '19 at 15:14