I am trying to fetch values from a Multidimensional array using foreach loop, i have understand the basics of foreach(){} loop, but when it comes to Multidimensional array i get confused.

This is my program

        $food        =array( 'Healthy'    => array('Salad','Rice',
                                                          'Vegetables'=>array('Tomatto','Onion')) ,
                            'UnHealthy'    => array('pasta',
                                                         'Vegetables'=>array('potatto', 'Corn'))    );

I want to print all vegetables in my output, i have tried various way to do it, and search a lot of examples but fond nothing useful. Kindly tell me the way to do it.


You can use a recursive function which checks if the value of the pair $key => $value is an array, in this case it loops again, an example:


    $food = array(
        'Healthy'   => array('Salad','Rice','Vegtables' => array('Tomatto','Onion')),
        'UnHealthy' => array('pasta', 'Vegetables' =>array('potatto', 'Corn')));

    function recursive_loop($array)
        foreach($array as $key => $value)
                echo $value . PHP_EOL;

    echo recursive_loop($food);

I am totally aggree with function made by @cereal. You can use that.

In addiotion to that function you can check $key. If key equal to "Vegetables" you can display value of "Vegetables"

Member Avatar

You could probably do the external call without the preceeding echo. SO this should work:

commented: Thanks! I didn't even thought about that! +11