MeltingDog MeltingDog - 1 year ago 84
PHP Question

PHP foreach for child of multidimentional array?

I have a multidimensional array as such:

$food= array
array("Rye" =>1, "Wheat" =>4, "White" =>4 ),
array("Apple" =>2, "Orange"=>1, "Banana"=>5 ), <---data I want
array("Cheese"=>2, "Milk" =>1, "Cream" =>5 )

Is there a way I can use a foreach loop to loop through the 2nd child array (fruit data)?

Answer Source

Like this?

foreach($food as $produce) {
    foreach($produce as $name => $value) {
        echo "The produce $name has value: $value\n";


The first for loop just loops through the first array, it doesn't have significant keys we need, so I just get the reference to the value and store it in the value $produce

Then, we loop through the array that is $produce, but this time key and value are both significant.

That's why we use $name => $value in this loop, so we get both values we need.
Some prefer to always use $key => $value, but I prefer to give variables the name of the value they represent.

Now if you need a specific fruit, you could wrap it in a function to search for it

 * Returns the fruit name from supplied food array.
 * @var $food array[array[string => value]]
 * @var $fruitName string The name of the fruit you want
 * @returns 
function findFruit($food,$fruitName) {
     foreach($food as $produce) {
        foreach($produce as $name => $value) {
            if($name == $fruitName) {
               return $value;
$quantityOfBananas = findFruit($food, "Banana");//5
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download