PHPwhile Loop

while Loop

A while loop repeats a block of code for as long as a condition stays true. What makes it different from other loops is when the check happens: the condition is evaluated before every pass through the body, including the very first one. If the condition is false the moment PHP reaches the loop, the body never runs at all — not even once. That single fact is the key to understanding almost everything else about while.

The basic shape

The syntax is a while keyword, a condition in parentheses, and a body wrapped in curly braces. PHP checks the condition, and only if it evaluates to true does it execute the body — then it jumps back up and checks again.

A simple countdown

PHP
<?php
$seconds = 5;

while ($seconds > 0) {
    echo "{$seconds}...\n";
    $seconds--;
}

echo "Liftoff!\n";
5...
4...
3...
2...
1...
Liftoff!
Pre-test behaviour: the body can run zero times

Because the condition is tested up front, a while loop is a "pre-test" loop. If you initialize the loop variable in a state that already fails the condition, the body is skipped entirely and execution moves straight to the line after the loop. This is different from a do-while loop, which always runs its body at least once because it checks the condition after the first pass.

Condition already false — body never runs

PHP
<?php
$stock = 0;

while ($stock > 0) {
    echo "Selling one unit...\n";
    $stock--;
}

echo "Done checking stock.\n";
Done checking stock.

Notice that "Selling one unit..." never printed. This is a common source of confusion for beginners who expect every loop to run at least once — while makes no such promise.

Accumulating a result

A very common real-world use of while is walking through a collection or a stream of values while keeping a running total. The example below sums the numbers from 1 to 10 using an accumulator variable and a counter that advances on each iteration.

Summing numbers 1 through 10

PHP
<?php
$i = 1;
$sum = 0;

while ($i <= 10) {
    $sum += $i;
    $i++;
}

echo "Sum: {$sum}\n";
Sum: 55

Three ingredients make this pattern work: a variable initialized before the loop ($i = 1), a condition that depends on that variable ($i <= 10), and a statement inside the body that moves the variable closer to failing the condition ($i++). Miss any one of the three and the loop either never runs, runs forever, or runs the wrong number of times.

Infinite loops: forgetting to update the condition

The single most common while bug is writing a condition that never becomes false, because the variable it depends on is never changed inside the body — or the wrong variable is changed instead. PHP has no built-in protection against this; it will happily loop forever (or until the script's execution time limit kills it, if one is configured).

Broken: $i is never incremented

PHP
<?php
$i = 1;

// BUG: nothing inside the loop changes $i, so $i <= 5 is always true
while ($i <= 5) {
    echo "Iteration\n";
    // forgot: $i++;
}
Runaway loop — this will hang the script
The example above prints `Iteration` forever, because `$i` is stuck at `1` and `1 <= 5` never stops being true. A closely related mistake is updating a *different* variable than the one the condition checks — for example incrementing `$count` while the condition tests `$i`. Always double-check that the variable you mutate inside the loop is the same one that appears in the condition, and that the mutation moves it in the direction that eventually makes the condition false.

Fixed: increment the variable the condition depends on

PHP
<?php
$i = 1;

while ($i <= 5) {
    echo "Iteration\n";
    $i++; // now $i eventually exceeds 5 and the loop ends
}
Iteration
Iteration
Iteration
Iteration
Iteration
The alternative syntax for templates

When PHP is mixed directly with HTML — for example in an old-school template file that is not using a templating engine — the curly-brace syntax gets visually noisy because you keep switching in and out of ?php ... ? tags. PHP offers an alternative syntax for while that replaces the opening brace with a colon and the closing brace with endwhile;, which reads more naturally when it is interleaved with markup.

Alternative syntax inside an HTML template

PHP
<?php
$items = ['Apples', 'Bananas', 'Cherries'];
$index = 0;
$count = count($items);
?>
<ul>
<?php while ($index < $count): ?>
    <li><?= $items[$index] ?></li>
    <?php $index++; ?>
<?php endwhile; ?>
</ul>

The behaviour is identical to the brace version — only the syntax changes. It exists purely for readability in files where PHP and HTML are interleaved line by line, and you will see it frequently in older codebases and in templates for content management systems.

Nesting and the loop variable's scope

while loops can be nested inside one another, just like if statements. Each loop needs its own condition variable — reusing the same variable name for an outer and inner loop is a classic way to accidentally break the outer loop's counting.

Nested while loops with distinct counters

PHP
<?php
$row = 1;

while ($row <= 3) {
    $col = 1;
    while ($col <= 3) {
        echo "({$row},{$col}) ";
        $col++;
    }
    echo "\n";
    $row++;
}
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)
Choosing while versus for or foreach
  • Reach for while when the number of iterations is not known ahead of time — for example, reading lines from a file until end-of-file, or retrying an operation until it succeeds.

  • Reach for a for loop when you know exactly how many times you want to iterate and the counting logic fits neatly on one line.

  • Reach for foreach when you are simply walking through every element of an array and do not need manual index bookkeeping at all.

  • Reach for do-while when the body must run at least once regardless of the condition — for example, showing a menu before asking whether to repeat it.

break and continue still apply
Just like other loop types, `while` respects `break` (exit the loop immediately) and `continue` (skip to the next condition check). These are useful for bailing out of a `while (true)` polling loop once a condition is met, without having to restructure the condition itself.
Tip
When a loop's exit condition is genuinely open-ended — such as "keep going until the API says there is no next page" — it is clearer to write `while (true) { ... if ($done) { break; } ... }` than to contort the loop's real exit logic into the `while(...)` condition itself. Readers immediately understand that the exit happens inside the body, rather than hunting for a subtle update to a boolean flag buried three lines down.