The PHP while Loop
A while loop keeps repeating its code for as long as its condition remains true.
Tip: PHP tests the condition before every pass, including the first. A condition that is false from the start means the code inside never runs at all.
Print numbers with while
$i starts at 1 and is printed and increased on each pass, until it is no longer below 6:
Output: PHP script
<?php
$i = 1;
while ($i < 6) {
echo $i;
$i++;
}
?>
While loop syntax
In its general form, a while loop looks like this:
while (condition) {
// code to be executed repeatedly as long as condition is true
}
The PHP break Statement
A break ends the loop on the spot, even when the condition would allow it to keep going.
Stop the loop with break
The loop ends when $i equals 3, leaving just 1 and 2 in the output:
Output: PHP script
<?php
$i = 1;
while ($i < 6) {
if ($i == 3) break;
echo $i;
$i++;
}
?>
The PHP continue Statement
The continue statement drops the rest of the current pass, and the loop moves on to the following one.
Skip iteration with continue
Because $i is increased before the check, the loop keeps moving, and only the number 3 is left out of the output:
Output: PHP script
<?php
$i = 0;
while ($i < 6) {
$i++;
if ($i == 3) continue;
echo $i;
}
?>
Alternative Syntax
A while loop can also be written without braces: put a colon after the condition and finish with endwhile.
While loop with endwhile
This version has the same effect as the first example, printing $i while it is below 6:
Output: PHP script
<?php
$i = 1;
while ($i < 6):
echo $i;
$i++;
endwhile;
?>
Step 10
A loop counter can grow by any amount. To reach 100 in steps of ten, add 10 to the counter on each pass instead of 1.
Count to 100 by tens
The counter is raised before it is printed, so the output runs from 10 to 100:
Output: PHP script
<?php
$i = 0;
while ($i < 100) {
$i+=10;
echo $i . "<br>";
}
?>