TExcelTAD
Home › PHP › PHP While Loops

PHP While Loops

Loops repeat a block of code. PHP has four loop statements: while, do...while, for and foreach. This lesson covers the two "condition" loops, which keep going as long as a condition stays true. They are the right choice when you don't know in advance how many repetitions you need.

Loop Checks the condition Runs at least once?
while before each pass no
do...while after each pass yes
for before each pass (counter built in) no
foreach — (walks through an array) no, for an empty array

The while loop

php
while (condition) {
    // repeated while condition is true
}

PHP evaluates the condition; if it is truthy, the body runs, then the condition is checked again. As soon as it becomes false, the program continues after the loop.

php · try it yourself
<?php
$countdown = 5;

while ($countdown > 0) {
    echo $countdown, "... ";
    $countdown--;
}

echo "Liftoff!\n";
5... 4... 3... 2... 1... Liftoff!

Something inside the body must eventually make the condition false — here $countdown--. If you forget it, the loop runs forever.

Note: If you accidentally write an infinite loop in a playground, it is stopped automatically after a time limit.

Loops with an unknown number of steps

while shines when the number of iterations depends on the data. How many years does it take for savings to double at 6% interest?

php · try it yourself
<?php
$balance = 1000.0;
$rate = 0.06;
$years = 0;

while ($balance < 2000) {
    $balance *= 1 + $rate;
    $years++;
}

printf("After %d years the balance is %.2f\n", $years, $balance);
After 12 years the balance is 2012.20

Another classic: the Collatz sequence. Halve even numbers, turn odd numbers into 3n + 1, and stop at 1.

php · try it yourself
<?php
$n = 6;
$steps = [$n];

while ($n !== 1) {
    $n = $n % 2 === 0 ? intdiv($n, 2) : 3 * $n + 1;
    $steps[] = $n;
}

echo implode(" -> ", $steps), "\n";
echo "Steps: ", count($steps) - 1, "\n";
6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
Steps: 8

The do...while loop

A do...while loop runs its body first and checks the condition afterwards. That guarantees at least one pass, even when the condition is false from the start. Note the semicolon after the closing while (...).

php · try it yourself
<?php
$n = 10;
do {
    echo "do...while ran with n = $n\n";
    $n++;
} while ($n < 5);

$m = 10;
while ($m < 5) {
    echo "while ran with m = $m\n";
    $m++;
}
echo "Done\n";
do...while ran with n = 10
Done

The while loop never ran because 10 < 5 is false before the first pass, but the do...while body executed once.

A typical real use is "try, then check": generate something, and repeat only if the result isn't acceptable — for example, retrying an operation or re-asking for input until it is valid. Here we keep dividing a number by 10 to count its digits; even 0 has one digit, so the body must run at least once:

php
$digits = 0;
do {
    $digits++;
    $number = intdiv($number, 10);
} while ($number > 0);

Alternative syntax

Like if, while has a colon form that reads nicely in templates:

php
<?php while ($row = next_row()): ?>
    <li><?= htmlspecialchars($row) ?></li>
<?php endwhile; ?>

Common mistakes

Mistake Result Fix
Never changing the loop variable infinite loop update it inside the body
Off-by-one (<= vs <) one pass too many or too few trace the first and last pass by hand
Missing ; after do {...} while (...) parse error end the statement with ;
Using = instead of ==/=== in the condition assignment, often infinite compare with ===

Tip: If you know exactly how many times to repeat (for example "10 times" or "once per array element"), a for or foreach loop is clearer. Keep while for "until something happens".

Test yourself

How many times does the body of do { ... } while (false); run?

  1. 0
  2. 1
  3. Forever
  4. It doesn't compile

What prints: $i = 3; while ($i > 0) { echo $i; $i -= 1; }?

  1. 321
  2. 3210
  3. 123
  4. 32

Which loop is the best fit for 'keep doubling until the value exceeds 1000'?

  1. foreach
  2. while
  3. switch
  4. match