PHP foreach Loop.

PHPServer Side ProgrammingProgramming

Introduction

The foreach statement is one of the looping constructs offered by PHP. Other looping statements − while, do while and for − are used to form a conditional or counted loop. On the other hand, foreach loop is very convenient for iterating over an array structure. Usage of foreach statement is as follows −

Syntax

foreach (array_expression as $value)
   statement
foreach (array_expression as $key => $value)
   statement

First form of foreach iterates over elements in an indexed array. On each iteration, the $value variable is set to current element in the array. PHP keeps track of the internal pointer by advancing to next element, till it reaches the end of array. Value of each elememt is processed by the body of loop that follows foreach statement

Second form is suitable for traversal of associative array. Every iteration unpacks current element in $key and $value variables. After body of the loop is processed, array pointer is advanced to next key-value pair till the array gets exhausted.

Following example traverses an indexed array with the help of foreach loop

Example

 Live Demo

<?php
$arr = array(2,4,6,8,10);
foreach ($arr as $i){
   echo $i . "*2=" . $i*2 . "\n";
}
?>

Output

This will produce following result −

2*2=4
4*2=8
6*2=12
8*2=16
10*2=20

Following example shows traversal of associative array with foreach loop

Example

 Live Demo

<?php
$arr = array("Phy"=>50, "Che"=>60, "Maths"=>70, "Bio"=>80);
foreach ($arr as $sub=>$marks){
   echo "marks in $sub: " . $marks . "\n";
}
?>

Output

This will produce following result −

marks in Phy: 50
marks in Che: 60
marks in Maths: 70
marks in Bio: 80

A two dimensional array is traversed using nested foreach loops

Example

 Live Demo

<?php
$arr1=[1,2,3,4,5];
$arr2=[6,7,8,9,10];
$twodim=[$arr1,$arr2];
foreach ($twodim as $row){
   foreach ($row as $col){
      echo $col . " ";
   }
   echo "\n";
}
?>

Output

This will produce following result −

1 2 3 4 5
6 7 8 9 10

Example

A two dimensional array of associative arrays is traversed in following example

Example

 Live Demo

<?php
$arr1=["rno"=>1, "name"=>"Kiran", "marks"=>50];
$arr2=["rno"=>2, "name"=>"anil", "marks"=>60];
$arr3=["rno"=>3, "name"=>"Bina", "marks"=>70];
$twodim=[$arr1,$arr2, $arr3];
foreach ($twodim as $row){
   foreach ($row as $k=>$v){
      echo $k . ":" . $v . " ";
   }
   echo "\n";
}
?>

Output

This will produce following result −

rno:1 name:Kiran marks:50
rno:2 name:anil marks:60
rno:3 name:Bina marks:70
raja
Published on 19-Sep-2020 16:41:49
Advertisements