For loop allows to repeat or iterate code, given number of times.
Syntax
for(initialization; condition; iteration){
// Code/set of statements
}
for (expr1; expr2; expr3)
statement
for loop has four parts
initialization | Specifies the starting value or number from where for loop starts. Initialization is done once. |
condition | it tests condition, if true executes the statements, else not. |
iteration | It is used to continue the loop, until condition becomes false, It can be increment or decrement. |
Statements | Statements are line of codes, enclosed inside curly braces { }. For single statement no need to use curly braces. |
Example
<?php
for($a = 1; $a <= 10; $a++)
{
echo $a;
}
?>
Above for loop, outputs number from 1 to 10; where,
$a = 1 | initialization |
$a <= 10 | condition |
$a++ | increment |
Single Statement for loop with no curly braces
<?php
for($a = 1; $a <= 10; $a++)
echo $a;
?>
Inside for loop, if there is single statement or line of code, then no need to use curly braces, more than one statement, curly braces are compulsory.