Beginner Tutorial – For each statement in PHP

As I created two categories healthy and unhealthy food and defines its child array so now I’m using this array in For each statement. Most of the website development company used these statement as their requirements.

 

<?php

 

$food = array (‘Healthy’=>

                                                   array (‘salad’,’vegetable’,’pasta’),

                        ‘Unhealthy’=>

                                                 array (‘Pizza’,’Icecream’));

?>

 

Now using for each statement in Multidimensional array. For each statement is used to display the list of Healthy and Un healthy food.

 

Syntax of For-each statement:-

 

 

foreach()

{

 

}

 

Now I’m using multidimensional array() in For-each statement

 

 

<?php

 

$food = array (‘Healthy’=>

array (‘salad’,’vegetable’,’pasta’) ,

 ‘Unhealthy’=>

array (‘Pizza’,’Icecream’) ) ;

 

foreach ($food as  $element => $inner_array )   {

 

echo $element . ’ <br> ’ ;

foreach ( $inner_array as $item) {

echo $items.’<br>’;

}

}

?>

 

We define $food as $element because by default element is used to define category as I used healthy and unhealthy. We can use HTML tags to give styling or to break lines and then echo inner_array as healthy and unhealthy food .Then I add $items as list such as salad , vegetable , pasta in it as I assign them in categories as u can see in array and then echo the result.

 

 

Here is the Output of following source code :-

 

Healthy

 

  • Salad
  • Vegetable
  • Pasta

 

Unhealthy

 

  • Pizza
  • Ice cream

 

PHP tutorials by web agency london