Sunday, 9 March 2014

Foreach Statement in php


Php Foreach loop
Foreach statement in php programming language. For Each statement refer to for each loop because it does loop through elements of array and allow as to each array over an array it take out different elements. Here i will use Multi-dimensional arrays with help of foreach statement i will display list of healthy and unhealthy foods.


Code for Foreach Statement (Screenshot1) :-

foreach statement php
Foreach Statement Screenshot1


<?php



$food = array('Healthy'=>array ('salad',Vegetables','Pasta');

'Unhealthy'=>array('Pizza','ice cream'));



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



echo $element.'
'; } ?>

Output (Screenshot2):-

php foreach statement
Screenshot2

In this example we will see practical use of Multi-dimensional arrays and then using this foreach statement to basically display there values. With keyword foreach we need to address array which is $food as $element. So, $food as
$element is taking which is healthy and unhealthy. $food as $element => $inner_element now in this $element is healthy and unhealthy and $inner_element addresses to array of  healthy and unhealthy such as salad, vegetables, pasta, pizza and ice cream. As you see output of $element is healthy and unhealthy. So, we had categorized two different element of array food. If i want inner_element of the array echo out here it will only display array. To find information about inner_element we need to loop again we already loop to find information of food array which is healthy and
unhealthy now for array of healthy and unhealthy we need to loop again.


Code for foreach statement (Screenshot3):-

foreach statement php
Screenshot3


<?php

$food = array('Healthy'=>array('salad',Vegetables','Pasta');

'Unhealthy'=>array('Pizza','icecream'));



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

echo $element.'
'; foreach($inner_array as $item){ echo $item.'
'; } } ?>



Output (Screenshot4):-

foreach statements php
Screenshot4
In this example i have changed name of  inner_element to inner_array you can see for taking loop for second to echo out the result of inner array. you see results is shown in category like healthy had items salad vegetables and pasta unhealthy had items like pizza and ice cream


No comments:

Post a Comment

Thanks For Comment Will get you Soon..

About Me

Welcome to Extra Tutorials! My name is Mohammed and I am the 22 year writer, website developer, and photographer behind the blog. Thanks for visiting! Tutorials Jackpot… In addition to Developer, I love to develop websites and I love to write. Starting a php Blog was inevitable for me. What began as a simple way to share all of my Tutorials with friends and family has developed into my Part time job.

Mohammed Padela

WHAT IS PHP PROGRAMMING

WHAT IS PHP PROGRAMMING
WHAT IS PHP PROGRAMMING

Follow Us

Popular Posts

Designed ByBlogger Templates