How to use Foreach in a multidimensional array in PHP

Asked

Viewed 533 times

0

I would like to know how to run the entire array only with Foreach:

$Marcas = array(array('Fiat', 'Volkswagen', 'Audi'),array('Yamaha', 'Suzuki', 'Honda'),array('Samsung', 'Motorola', 'Apple')); 

1 answer

1

A multidimensional array would normally be traversed with a double foreach. In your case with:

foreach ($Marcas as $subMarcas){
    foreach ($subMarcas as $marca){
        //código aqui
    }
}

However I got the idea that I wanted to do something with just one foreach. Can do this if you get an array that matches the merge of all subarrays.

For this you can use call_user_func_array passing as first parameter "array_merge" and as per the tag array, and then just iterate normally:

$marcas = call_user_func_array("array_merge", $Marcas);
foreach ($marcas as $marca){
    //código aqui
}

You can even do it on a śo line if you want:

foreach (call_user_func_array("array_merge", $Marcas) as $marca){
    //código aqui
}

See this last example in Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.