Hello,

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

    <?php
        $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.

Thanks

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:

<?php

    $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)
        {
            if(is_array($value))
            {
                recursive_loop($value);
            }
            else
            {
                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 for diafol

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

recursive_loop($food);
commented: Thanks! I didn't even thought about that! +11
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.