The for loop is used when you know in advance how many times the script should run. It gathers the initialization, condition, and increment logic into a single line, making your code extremely concise.
The for loop takes three parameters, separated by semicolons:
for (init counter; test counter; increment counter) {
// code to be executed for each iteration;
}
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
You can also use the for loop to count down by using a decrement operator.
<?php
for ($x = 10; $x >= 0; $x--) {
echo "Countdown: $x <br>";
}
?>
The increment part doesn't have to be $x++. You can increase by any value you wish.
<?php
for ($x = 0; $x <= 100; $x += 10) {
echo "Step: $x <br>";
}
?>
for loop can be left empty (e.g., for (;;)), but you must still provide the semicolons.
for loop whenever the number of iterations is fixed, such as printing the days of a month or headers for a table.
$x += 5).