while Loops

Loops repeat code. A while loop keeps going as long as its condition is true — the right choice when you don't know in advance how many repetitions you need, such as reading a file until it ends or retrying until something succeeds.

while

The condition is checked before each pass. If it's false at the start, the body never runs:

PHP
<?php

$countdown = 5;

while ($countdown > 0) {
    echo $countdown, " ";
    $countdown--;
}
echo "Lift-off!\n";
Output
5 4 3 2 1 Lift-off!

Something in the loop must eventually make the condition false. If not, the loop runs forever — on the command line press Ctrl+C; on a web server, PHP stops the script when it exceeds max_execution_time (30 seconds by default).

When the count isn't known

How many years until savings double at 5% interest? A while loop finds out:

PHP
<?php

$balance = 1000.0;
$years = 0;

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

printf("%d years, final balance %.2f\n", $years, $balance);
Output
15 years, final balance 2078.93

do-while

A do-while loop checks the condition after each pass, so the body runs at least once:

PHP
<?php

do {
    $roll = random_int(1, 6);
    $tries = ($tries ?? 0) + 1;
} while ($roll !== 6);

echo "Rolled a 6 after at least one try: ", $tries >= 1 ? "yes" : "no", "\n";
Output
Rolled a 6 after at least one try: yes

break and continue

break leaves the loop immediately; continue skips to the next pass:

PHP
<?php

$n = 0;
while (true) {
    $n++;
    if ($n % 3 === 0) {
        continue;          // skip multiples of 3
    }
    if ($n > 10) {
        break;             // stop completely
    }
    echo $n, " ";
}
echo "\n";
Output
1 2 4 5 7 8 10

while (true) with a break inside is a readable pattern when the exit test belongs in the middle of the loop.

Reading input until it ends

Many functions return false when there's nothing left — fgets for lines of input, fgetcsv for CSV rows, database cursors for rows. A while loop with an assignment in its condition processes everything:

PHP
<?php

$lines = 0;
$words = 0;

while (($line = fgets(STDIN)) !== false) {
    $lines++;
    $words += str_word_count($line);
}

echo "$lines lines, $words words\n";
Input
The quick brown fox
jumps over

the lazy dog
Output
4 lines, 9 words

The parentheses around ($line = fgets(STDIN)) matter: assign first, then compare. And compare with !== false, not just truthiness — a line containing "0" would otherwise end the loop early.

Processing until empty

array_shift removes and returns the first element of an array, so a loop can work through a queue until nothing is left:

PHP
<?php

$jobs = ["resize image", "send email", "write log"];

while ($jobs !== []) {
    $job = array_shift($jobs);
    echo "Running: $job (", count($jobs), " left)\n";
}
Output
Running: resize image (2 left)
Running: send email (1 left)
Running: write log (0 left)

Retrying with a limit

When retrying something that might fail, always cap the number of attempts so a permanent failure can't loop forever:

PHP
<?php

$attempt = 0;
$maxAttempts = 5;
$succeeded = false;

while (!$succeeded && $attempt < $maxAttempts) {
    $attempt++;
    $succeeded = $attempt === 3;     // pretend the third attempt works
    echo "Attempt $attempt: ", $succeeded ? "ok" : "failed", "\n";
}
Output
Attempt 1: failed
Attempt 2: failed
Attempt 3: ok

Try it yourself

The Collatz sequence: halve even numbers, and turn odd ones into 3n + 1. Count the steps to reach 1.

Try it yourself · main.php
Edit the code, copy it into main.php, then run it with php main.php (PHP 8.5). How to install PHP
Output
27 reaches 1 after 111 steps (peak 9232).