user2066103 user2066103 - 1 year ago 90
PHP Question

print keys and value of of php multidiamensional array

I am php beginner. I have a multidimensional array as follows.

$mainArray = array();

$mainArray['apple'] = array();
$mainArray['apple'][0] = 'fruit';
$mainArray['apple'][1] = 'red';

$mainArray['banana'] = array();
$mainArray['banana'][0] = 'fruit';
$mainArray['banana'][1] = 'yellow';

$mainArray['spinach'] = array();
$mainArray['spinach'][0] = 'vegetable';
$mainArray['spinach'][1] = 'green';

I want to get an output as follows:

apple is fruit
apple is red
banana is fruit
banana is yellow
spinach is vegetable
spinach is green

I am struggling to use a
loop in PHP to find the first key which is
apple, banana or spinach
.. any help will be appreciated. Thank you so much

Answer Source
foreach ($mainArray as $type => $descriptions) {
    foreach ($descriptions as $description) {
        echo $type . ' is ' . $description, PHP_EOL;

If you need to output them in a specific order, sort your array before using something simple like the above example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download