The PHP for Loop
Reach for a for loop when you know in advance how many times the code has to run. All the details that control the repetition sit together in one line at the top of the loop.
That line has three parts:
initialization- runs one time, before the loop starts, and usually sets up a counter variablecondition- is tested before every iteration; the loop keeps going while it is trueincrement- runs after every iteration and usually raises or lowers the counter
Print numbers from 0 to 10
This loop counts from 0 up to and including 10, printing each number:
Output: PHP script
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
For loop syntax
Written out in general form, a for loop looks like this:
for (initialization; condition; increment) {
// code to be executed
}
Example Explained
Let's walk through that example. First, $x = 0; runs a single time and gives the counter its starting value. Before every pass, PHP checks $x <= 10;, and the loop goes on only if the result is true, which is the case while $x has not gone past 10. After every pass, $x++; adds one to $x.
Decrease Counter Variable
Counters don't have to go up. Start high and subtract on each pass, and the loop counts backwards, as the next example shows.
Print numbers from 10 to 0
Starting at 10, $x-- lowers the counter until it reaches 0:
Output: PHP script
<?php
for ($x = 10; $x >= 0; $x--) {
echo "The number is: $x <br>";
}
?>
The PHP break Statement
A for loop can be ended early with break, even while its condition is still true.
Stop the loop with break
The loop is set up to reach 10, but it ends when $x equals 3, so only 0, 1 and 2 are printed:
Output: PHP script
<?php
for ($x = 0; $x <= 10; $x++) {
if ($x == 3) break;
echo "The number is: $x <br>";
}
?>
The PHP continue Statement
If you only want to skip one pass rather than end the loop, use continue. PHP abandons that iteration and moves on to the following one.
Skip iteration with continue
Every number from 0 to 10 is printed except 3:
Output: PHP script
<?php
for ($x = 0; $x <= 10; $x++) {
if ($x == 3) continue;
echo "The number is: $x <br>";
}
?>
Step 10
The increment doesn't have to be 1. Adding 10 on every pass gives you a loop that counts in tens.
Count to 100 by tens
Using $x+=10 as the increment, this for loop goes from 0 to 100 in steps of ten:
Output: PHP script
<?php
for ($x = 0; $x <= 100; $x+=10) {
echo "The number is: $x <br>";
}
?>