PHP while Loop
In this page:
Simple while Loop
A while loop checks its condition *before* running the body, and keeps re-running that body for as long as the condition stays true. If the condition is false on the very first check, the loop body never executes at all — not even once.
Example: Simple while Loop
<?php
$i = 1;
while ($i <= 5) {
echo $i . "\n";
$i++;
}
?>
Login to try C/C++/Java/PHP code in the editor
Decrementing Loop Counters
Counting down inside a while loop just means subtracting from the loop variable each pass instead of adding to it — the loop mechanics don't change, only the direction the variable moves and, correspondingly, the condition you check against.
Example: Decrementing Loop Counters
<?php
$i = 5;
while ($i > 0) {
echo $i . "\n";
$i--;
}
?>
Login to try C/C++/Java/PHP code in the editor
Loops with Boolean Flags
Using a boolean flag as the loop's condition lets code *inside* the loop body decide when to stop, simply by setting that flag to false — useful when the stopping condition depends on something discovered partway through an iteration rather than a value known up front.
Example: Loops with Boolean Flags
<?php
$keepGoing = true;
$count = 0;
while ($keepGoing) {
$count++;
echo $count . "\n";
if ($count == 3) {
$keepGoing = false;
}
}
?>
Login to try C/C++/Java/PHP code in the editor
Alternative while Syntax
The colon-based alternative syntax (while (...): ... endwhile;) behaves identically to the brace form but reads more cleanly when a loop is interleaved directly with HTML markup in a template file.
Example: Alternative while Syntax
<?php $i = 1; ?>
<?php while ($i <= 3): ?>
<p>Item <?php echo $i; ?></p>
<?php $i++; ?>
<?php endwhile; ?>
Login to try C/C++/Java/PHP code in the editor
Mathematical Loops
Multiplying or halving a variable each iteration — rather than adding or subtracting a fixed amount — produces exponential growth or decay, which is the pattern behind things like doubling capacity or repeatedly halving a search range.
Example: Mathematical Loops
<?php
$value = 1;
while ($value < 100) {
echo $value . "\n";
$value *= 2;
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: