PHP while Loop
The PHP while Loop
The PHP while loop - Loops through
a block of code as long as the specified condition is true.
Syntax
while (condition) {
// code to be executed repeatedly as long as condition is true
}Tip: The condition is checked at the beginning of each iteration, which means that if the condition is initially false, the code block will not run even once.
Example
Print $i as long as $i is less than 6:
$i = 1; // Initialize counter
while ($i < 6) { // Check condition
echo $i; // Execute code
$i++; // Increment counter
}
Try it Yourself »
Note: Remember to increment the counter
($i), or else the loop will continue forever.
The condition does not have to be a counter, it could be the status of an operation or any condition that evaluates to either true or false.
The PHP break Statement
With the break statement we can stop the loop even if the condition is still true:
Example
Stop the loop when $i is 3:
$i = 1;
while ($i < 6) {
if ($i == 3) break;
echo $i;
$i++;
}
Try it Yourself »
The PHP continue Statement
With the continue statement we can
skip the current iteration, and continue with the next:
Example
Skip, and move to the next iteration if $i is 3:
$i = 0;
while ($i < 6) {
$i++;
if ($i == 3) continue;
echo $i;
}
Try it Yourself »
Alternative Syntax
The while loop syntax can also be written with the
endwhile statement like this
Example
Print $i as long as $i is less than 6:
$i = 1;
while ($i < 6):
echo $i;
$i++;
endwhile;
Try it Yourself »
Step 10
If you want the while loop
count to 100, but only by each 10, you can increase the counter by 10 instead 1 in each iteration:
Example
Count to 100 by tens:
$i = 0;
while ($i < 100) {
$i+=10;
echo $i "<br>";
}
Try it Yourself »