PHP foreach Loop



We have studied for loop in the previous chapter. In this chapter we will be learning for each loop in PHP.

PHP foreach loop :

Foreach loop is used for the iteration of the array in PHP.

foreach ($array as $value)
{
  //code to be executed;
}

In the syntax –

$array <=====> Name of the array
$value <=====> Selection of single value from array

Example #1 : For each loop to iterate simple array

<!DOCTYPE html>
<html>
<body>

<?php 
$shapes = array("circle","square","rectangle","oval"); 
foreach ($shapes as $value)
   {
   echo "Shape : $value <br>";
   }
?>   

</body>
</html>

Output :

Shape : circle 
Shape : square 
Shape : rectangle 
Shape : oval

Explanation of the program :

Consider the following syntax –

$shapes = array("circle","square","rectangle","oval");

Using this line we can declare an simple array in PHP. Now instead of iterating array using traditional approach, PHP have provided us different approach to iterate an array list –

foreach ($shapes as $value)
{
 echo "Shape : $value <br>";
}

Using this statement we can select first value of array in first iteration. 2nd value of array in second iteration. This loop continues until the array list becomes empty.

Iteration Value of $value
Iteration 1 circle
Iteration 2 square
Iteration 3 rectangle
Iteration 4 oval

Example #2 : For each loop to iterate simple array

This example is for reference only. We will learn associative array in coming chapters.

<!DOCTYPE html>
<html>
<body>

<?php 

$studentMarks;
$studentMarks["Rajesh"] = "90";
$studentMarks["Sanjiv"] = "87";
$studentMarks["Suresh"] = "67";
$studentMarks["Anurag"] = "67";
$studentMarks["Pratik"] = "84";

foreach( $studentMarks as $key => $value){
	echo "$key got $value marks <br />";
}

?>   

</body>
</html>

Output :

Rajesh got 90 marks 
Sanjiv got 87 marks 
Suresh got 67 marks 
Anurag got 67 marks 
Pratik got 84 marks