For Statement(Loop) in PHP : Tutorial


For loop in PHP same as that in any other language like C or Java. For loop is widely used looping statement.

Syntax :
for ( expression1 ; expression2 ; expression3) {
    statement or block of statements
    }
expression1 is executed only once at the beginning of the for loop.

In the beginning of each iteration, expression2 is evaluated. If it evaluates to TRUE, the loop continues and the block of statements enclosed within for loop are executed. If it evaluates to FALSE, loop execution is terminated.

At the end of each iteration, expression3 is evaluated/executed.

Example :
<?php

for ($i = 1; $i <= 10; $i++) {
    echo $i."<br>";
}

?>
Output

1 2 3 4 5 6 7 8 9 10
In the above example,
$1=1 is the expression1 which is executed only once, so expression1 sets value of i as 1.
Then expression2 i.e. $i <= 10 is evaluated ( 1 < 10, which is true in this case).
Till expression2 holds true, expression3 is also executed i.e. $i++.

Nested for Loop Statements in PHP

<?php

for ($i = 1; $i <= 5; $i++) {
	for($j=1; $j<=10;$j++) {
		echo $i." x ".$j."= ".$i*$j."<br>";
	}
    echo "<br>";
}

?>
Output

1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 1 x 4 = 4 1 x 5 = 5 1 x 6 = 6 1 x 7 = 7 1 x 8 = 8 1 x 9 = 9 1 x 10 = 10 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10 2 x 6 = 12 2 x 7 = 14 2 x 8 = 16 2 x 9 = 18 2 x 10 = 20 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15 3 x 6 = 18 3 x 7 = 21 3 x 8 = 24 3 x 9 = 27 3 x 10 = 30 4 x 1 = 4 4 x 2 = 8 4 x 3 = 12 4 x 4 = 16 4 x 5 = 20 4 x 6 = 24 4 x 7 = 28 4 x 8 = 32 4 x 9 = 36 4 x 10 = 40 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50

Foreach loop with Arrays

(this is also covered with Arrays link)

The foreach loop provides an easy way to iterate values for arrays.
There are two syntaxes:

Syntax 1 :
foreach (array_expression as $value)
    statement
Syntax 2 :
foreach (array_expression as $key => $value)
    statement

Examples :
<?php
$genre_array = array("Rock","Pop","Jazz");

//Syntax 1 example
foreach ($genre_array as &$value) {
    echo $value."<br>";
}

//Syntax 2 example
$genre_array = array(		
	"artist" =>"Nirvana",
	"album" => "Nevermind",
	"song" => "Smells like teen spirit");
	
foreach ($genre_array as $key => $value) {
	echo "Key : ".$key."  -  Value :".$value."<br>";
}
?>
Output

Rock Pop Jazz Key : artist - Value :Nirvana Key : album - Value :Nevermind Key : song - Value :Smells like teen spirit