The for loop
The for loop is used to execute a set of statements for a certain number of times.
Syntax:
for (init; condition; increment/decrement) { code to be executed; }
Components of for loop:
- init: set a counter variable and initialize it to a numeric value.
- condition: evaluates the condition statement, if TRUE the loop will continue if FALSE, the loop ends.
- increment/decrement: increment or decrement the counter by how much we want.
Example:
<?php for ($num = 1; $num <= 10; $num++) { echo "$num "; } ?>
In our example we have set counter variable $num to 1.
In our condition the loop will continue to execute as long as the value of $num is less than or equal to ten.
The counter variable $num will increment by 1 each time the loop executes.
Result:
1 2 3 4 5 6 7 8 9 10