PHP For Each Loop


 

PHP For Each Loop

In this tutorial we will study about foreach loop, foreach loop is newly introduced in PHP and mainly it works on array. Examples in this tutorial will make it more clear.

In this tutorial we will study about foreach loop, foreach loop is newly introduced in PHP and mainly it works on array. Examples in this tutorial will make it more clear.

Foreach Loop in PHP

In PHP  associative array gives us more power to use arrays in more effective way, like we can associate any key with a value. To fetch values from associative array or a simple array we need to use for each loop.

Using  for each loop we can assign values of one by one to a variable and that variable is used inside the loop for various purpose like displaying the values of array, doing mathematical calculation etc.

For each loop can not be used on variables, otherwise an error message will be issued.

Nowadays for-each loop is being used by almost every language like Java, C# etc.

Format of the foreach loop is as follows:

foreach(array as $val)

statement

or

foreach(array as $key=>$val)

statement

Following examples will help you to learn for each loop precisely:

Example:

<?php

$studentClass;

$studentClass["ram"]="5";

$studentClass["rahim"]="5";

$studentClass["mohan"]="4";

$studentClass["joseph"]="5";

$studentClass["salma"]="2";

foreach($studentClass as $key => $value){

echo "$key reads in class $value <br/>";}

?>

Output:

ram reads in class 5
rahim reads in class 5
mohan reads in class 4
joseph reads in class 5
salma reads in class 2

Example:

<?php

$arr=array(1,2,3,4,5);

foreach($arr as $var):

echo $var.'<br/>';

0

endforeach;

?>

Output:

1

1
2
3
4
5

Ads