Skip to content
Advertisement

Merging 3 arrays in PHP

I have 3 arrays as below.

$array1 = Array
(
    [0] => 05/01
    [1] => 05/02
)

$array2 =Array
(
    [0] => ED
    [1] => P
)

$array3 =Array
(
    [0] => Mon
    [1] => Tue

)

I want to merge these 3 arrays as below $result_array. I have written a code as below. But It gave a empty array.

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

Code:

for($z=0; $z<count($array1); $z++){
    $all_array[$z][] = array_merge($array1[$z],$array2[$z] );
    $all_array2[$z] = array_merge($all_array[$z],$array3[$z] );
}

Please help me to do this.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement