This section contains detail about for & foreach Loop in PHP.
for & foreach Loop in PHP
In PHP, for & foreach loop executes code block a specific number of times, or until condition fails.
The for Loop
The for loop executes a block of until condition fails. Given below the syntax :
for (init; condition; increment) { code for execution; }
In the above, init is initialization parameter, condition is used to check condition at every iteration until condition is true and increment is used to set counter. You can use this counter for setting condition as given in the next example.
Given below the example :
<html> <body> <?php for ($j=1; $j<=3; $j++) { echo "Value of counter is " . $j . "<br />"; } ?> </body> </html>
Output :
Value of counter is 1
Value of counter is 2
Value of counter is 3
The foreach Loop
To loop through array, we use foreach in PHP.
Syntax of foreach is given below :
foreach ($array as $value) { code to be executed; }
In every iteration the $value holds the current array element and pointer moves one step further to loop.
Given below the example :
<html> <body> <?php $a=array("first","second","third"); foreach ($a as $value) { echo $value . "<br />"; } ?> </body> </html>
Output :
first
second
third
Other form of foreach
Syntax is given below :
foreach (array_expression as $key => $value) { statement }
Here array_expression is array whose current element's key will be assigned to the variable $key on each loop. Rest is same as previous foreach.
Given below the example :
$studentAges; $studentAges["Ankita"] = "25"; $studentAges["Shekhar"] = "26"; $studentAges["Shivangi"] = "25"; $studentAges["Kapil"] = "26"; $studentAges["Samita"] = "24"; foreach( $studentAges as $name => $age){ echo "Name: $name, Age: $age
"; }
Here $name holds the current element key and $age holds the value. Output is given below :
Output :
Name: Ankita, Age: 25
Name: Shekhar, Age: 26
Name: Shivangi, Age: 25
Name: Kapil, Age: 26
Name: Samita, Age: 24
[ 0 ] Comments