PHP for loop is the most complex loops in PHP. They behave like their C counterparts.
Syntax of PHP for loop:
Following is given a general syntax of for loop in PHP:
1 2 3 4 |
for(initialization; condition ; increment/decrement) { //statements; } |
In the beginning, loop condition is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed.
If it evaluates to FALSE, the execution of the loop ends.
All three expression, initialization, condition, increment/decrement can be empty or multiple.
If the condition is empty then loop will execute infinite considering it is true.
If the expressions are multiple then they are separated by commas.
Flowchart of PHP for loop
Example
Consider the following examples.
1 2 3 4 5 6 |
<?php for($a = 0; $a <= 5; $a++) { echo "a = $a<br>"; } ?> |
Output:
1 2 3 4 5 6 |
a = 0 a = 1 a = 2 a = 3 a = 4 a = 5 |