While Loop
What Is a while Loop? In simple terms: A while loop keeps repeating a block of code as long as a condition is true. It checks the condition before every repetition. Technically: while evaluates its co
What Is a while Loop?
In simple terms: A while loop keeps repeating a block of code as long as a condition is true. It checks the condition before every repetition.
Technically: while evaluates its condition; if the result (converted to boolean) is true, it executes the body and then evaluates the condition again. When the condition becomes false, execution continues after the loop. Because the condition is checked first, the body may run zero times.
Why It Is Needed
while is the right loop when you do not know in advance how many repetitions are needed:
- Read lines from a file until there are no more.
- Process jobs from a queue until it is empty.
- Retry an operation until it succeeds or a limit is reached.
- Repeat a calculation until a target value is reached.
Syntax
while (condition) {
// code to repeat
}
Flow
┌─────────────┐
┌───►│ condition ? │── false ──► continue after the loop
│ └──────┬──────┘
│ true
│ ▼
│ [ loop body ]
└───────────┘
Example: Countdown
<?php
$seconds = 5;
while ($seconds > 0) {
echo "Starting in $seconds...\n";
$seconds--;
}
echo "Started!\n";
Output
Starting in 5...
Starting in 4...
Starting in 3...
Starting in 2...
Starting in 1...
Started!
How It Works
$secondsstarts at 5.- Before each iteration, PHP checks
$seconds > 0. - The body prints a message and decreases
$secondsby 1. - After the fifth iteration,
$secondsis 0, the condition is false, and the loop ends.
The line $seconds--; is essential: it moves the loop toward its end condition. Without it, the condition would stay true forever.
The Body May Not Run at All
<?php
$stock = 0;
while ($stock > 0) {
echo "Selling one item\n";
$stock--;
}
echo "Done (stock: $stock)\n";
Output
Done (stock: 0)
The condition is false from the start, so the body never runs. This is the key difference from do...while, which always runs its body at least once (see Do While Loop).
Repeating Until a Target Is Reached
while naturally expresses "keep going until …":
<?php
$balance = 10000;
$annualRate = 0.08;
$years = 0;
while ($balance < 20000) {
$balance *= 1 + $annualRate;
$years++;
}
echo "It takes $years years to double the investment.\n";
echo "Final balance: ₹" . number_format($balance, 2) . "\n";
Output
It takes 10 years to double the investment.
Final balance: ₹21,589.25
How It Works
- Each iteration applies one year of 8% growth and counts the year.
- The loop stops as soon as the balance reaches ₹20,000 or more.
- You did not need to know the number of years in advance — the condition decides.
Processing Digits of a Number
<?php
$number = 4729;
$sum = 0;
while ($number > 0) {
$sum += $number % 10; // last digit
$number = intdiv($number, 10); // remove last digit
}
echo "Digit sum: $sum\n";
Output
Digit sum: 22
% 10 extracts the last digit, and intdiv($number, 10) removes it. The loop runs once per digit — however many digits the number has.
Reading Data Until It Runs Out
A very common while pattern assigns a value in the condition and stops when the source returns false or null.
Reading Lines From a Stream
<?php
$stream = fopen('php://memory', 'r+');
fwrite($stream, "apple\nbanana\ncherry\n");
rewind($stream);
$lineNumber = 0;
while (($line = fgets($stream)) !== false) {
$lineNumber++;
echo "$lineNumber: " . trim($line) . "\n";
}
fclose($stream);
Output
1: apple
2: banana
3: cherry
How It Works
php://memoryis a temporary in-memory stream, used here so the example needs no file on disk.fwrite()adds text andrewind()moves back to the start.fgets()returns the next line, orfalsewhen there are no more lines.($line = fgets($stream)) !== falseassigns the line and checks it in one step. The parentheses are required, and the strict comparison matters: a line containing only"0"is falsy but valid.trim()removes the newline at the end of each line.
The same pattern reads real files (fopen('data.txt', 'r')), CSV rows (fgetcsv()), and database results.
Processing a Queue
<?php
$queue = ['resize photo-1.jpg', 'resize photo-2.jpg', 'send welcome email'];
while ($queue !== []) {
$task = array_shift($queue);
echo "Processing: $task (" . count($queue) . " left)\n";
}
Output
Processing: resize photo-1.jpg (2 left)
Processing: resize photo-2.jpg (1 left)
Processing: send welcome email (0 left)
array_shift() removes the first element, so the array shrinks with each iteration until it is empty.
Retrying With a Limit
When an operation may fail temporarily (a network call, for example), while can retry it — but always with a maximum number of attempts.
<?php
// Simulated results of three attempts: fail, fail, succeed
$simulatedResults = [false, false, true];
$maxAttempts = 5;
$attempt = 0;
$success = false;
while (!$success && $attempt < $maxAttempts) {
$attempt++;
$success = $simulatedResults[$attempt - 1] ?? true;
echo "Attempt $attempt: " . ($success ? "success" : "failed") . "\n";
}
echo $success ? "Completed after $attempt attempt(s)\n" : "Gave up after $maxAttempts attempts\n";
Output
Attempt 1: failed
Attempt 2: failed
Attempt 3: success
Completed after 3 attempt(s)
Why Both Conditions Matter
!$successstops the loop as soon as an attempt succeeds.$attempt < $maxAttemptsguarantees the loop ends even if the operation never succeeds — preventing an infinite loop.
In real code, the simulated array would be replaced by the actual operation, and a short delay (for example usleep()) is often added between attempts.
while (true) With break
Sometimes the exit condition is easiest to check in the middle of the loop. An intentional infinite loop with break expresses this:
<?php
$commands = ['status', 'help', 'quit', 'status'];
while (true) {
$command = array_shift($commands);
if ($command === null || $command === 'quit') {
echo "Exiting\n";
break;
}
echo "Running command: $command\n";
}
Output
Running command: status
Running command: help
Exiting
The loop processes commands until it reads quit (or runs out), so the last status is never executed. Every while (true) loop must have a reachable break or return.
Alternative Syntax
In templates, while can use endwhile;:
<?php $remaining = 3; ?>
<?php while ($remaining > 0): ?>
<span>Seat <?= $remaining ?> available</span>
<?php $remaining--; ?>
<?php endwhile; ?>
Output (HTML)
<span>Seat 3 available</span>
<span>Seat 2 available</span>
<span>Seat 1 available</span>
foreach is more common in templates, but this form works the same way.
Common Mistakes
Forgetting to Change the Condition
$i = 1;
while ($i <= 3) {
echo $i;
}
Effect: Infinite loop — $i never changes.
Fix: Update the variable inside the loop ($i++).
Updating in the Wrong Direction
$i = 10;
while ($i > 0) {
$i++; // should be $i--
}
Effect: The condition stays true forever (until the integer overflows to a float, which is still greater than 0).
Fix: Make sure each iteration moves toward making the condition false.
Loose Checks When Reading Data
Effect: while ($line = fgets($stream)) stops early at a line containing "0", because "0" is falsy.
Fix: Compare strictly: while (($line = fgets($stream)) !== false).
Retrying Without a Limit
Effect: A permanently failing operation causes an endless loop.
Fix: Always add a maximum attempt count.
Using while Where foreach Fits
Effect: Manual index handling and off-by-one errors when iterating arrays.
Fix: Use foreach for arrays; use while for "until" conditions.
Best Practices
- Use
whilewhen the number of iterations depends on data or results, not on a fixed count. - Make sure every iteration moves toward the end condition.
- Use strict comparisons (
!== false,!== null) when assigning in the condition. - Add attempt limits to retry loops, and a reachable
breaktowhile (true)loops. - Prefer
forfor counting andforeachfor arrays.
Official reference: https://www.php.net/manual/en/control-structures.while.php