Merging 3 arrays in PHP

this work for n of arrays and dynamic length of array

function mergeArrays(...$arrays)
{

    $length = count($arrays[0]);
    $result = [];
    for ($i=0;$i<$length;$i++)
    {
        $temp = [];
        foreach ($arrays as $array)
            $temp[] = $array[$i];

        $result[] = $temp;
    }

    return $result;

}

$x = mergeArrays(['05/01' , '05/02'] , ['ED' , 'P'] , ['Mon' , 'Tus']);
$y = mergeArrays(['05/01' , '05/02' , 'X'] , ['ED' , 'P' , 'Y'] , ['Mon' , 'Tus' , 'Z'] , ['A' , 'B' , 'C']);

var_dump($x);
var_dump($y);

Simply foreach over the first array and use the index as the key to the other arrays.

foreach ( $array1 as $idx => $val ) {
    $all_array[] = [ $val, $array2[$idx], $array3[$idx] ];
}

Remember this will only work if all 3 arrays are the same length, you might like to check that first


Create an sample array and push to each array value with respective key

$sample = array();
for($z=0; $z<count($array1); $z++){
    $sample[]=array($array1[$z],$array2[$z],$array3[$z]);
}
print_r($sample);

Out put is

Array ( [0] => Array ( 
               [0] => 05/01 
               [1] => ED 
               [2] => Mon 
        ) 
        [1] => Array ( 
               [0] => 05/02 
               [1] => P 
               [2] => Tue 
        ) 
)

You can simply walk through the first array with a foreach loop then access the corresponding arrays and combine the results into one big array. This will only work if the arrays are the same length so it's worth checking that before to stop any errors. Something like this:

<?php
$arr1 = ['05/01', '05/02'];
$arr2 = ['ED', 'P'];
$arr3 = ['Mon', 'Tue'];

$combined = [];
if (count($arr1) != count($arr2) || count($arr1) != count($arr3))
  die("Array lengths do not match!");

foreach ($arr1 as $key => $val) {
    $combined[] = [$val, $arr2[$key], $arr3[$key]];
}

var_dump($combined);

You can see an eval.in of this working here - https://eval.in/833893