← Back to PHP Course | Chapter 4: Control Flow | Lesson 10 of 14

PHP while Loop

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
<?php
$i = 1;
while ($i <= 5) {
    echo $i . "\n";
    $i++;
}
?>

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
<?php
$i = 5;
while ($i > 0) {
    echo $i . "\n";
    $i--;
}
?>

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
<?php
$keepGoing = true;
$count = 0;
while ($keepGoing) {
    $count++;
    echo $count . "\n";
    if ($count == 3) {
        $keepGoing = false;
    }
}
?>

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
<?php $i = 1; ?>
<?php while ($i <= 3): ?>
  <p>Item <?php echo $i; ?></p>
  <?php $i++; ?>
<?php endwhile; ?>

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
<?php
$value = 1;
while ($value < 100) {
    echo $value . "\n";
    $value *= 2;
}
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.