Posted By:
9 Mar, 2014 12:09 am PST

How to write foreach loop in PHP?

 How to write foreach loop in PHP?

foreach()loop provide useful and efficient way of handling arrays in loop. foreach() does not contain any initialization, condition and incrementing/decrementing.



foreach ($arrayName as $value)


//write your code here




echo "<h2 >";


echo "To find square of the number present in the array <br ><br >";


$numArray = array (10 ,5 ,6 ,7 ,8 ,11 ,15 ,13);


echo " Square of the number as follows ..... <br ><br >";


foreach ( $numArray as $num )// array as value




      $sqr = $num * $num ;// statements


       echo " Square of { $num } is { $sqr } <br ><br >";


















 The foreach() loop iterate through an array and treat each array element as an individual

Variable until it reaches to last element in the array. every time loop iterates value of next element of array copied into $value.



Attachment: ForEachLoop.php

How to use foreach loop in PHP

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects. There are two syntaxes:


foreach(array_expression as $value)


foreach (array_expression as $key => $value)


//Code to show how to use foreach loop



$marks["Maths"] = "91";
$marks ["Science"] = "99";
$marks ["English"] = "95";
$marks ["hindi"] = "88";
$marks ["English Grammar"] = "89";

foreach( $marks as $key => $value){
echo "Subject: $key, Marks: $value <br />";


/*Output of the above program is:
Subject: Maths, Marks: 91
Subject: Science, Marks: 99
Subject: English, Marks: 95
Subject: hindi, Marks: 88
Subject: English Grammar, Marks: 89


Was it useful?  

Please login to reply to this problem.