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];
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];
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];
}
}
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.
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];
}