PHP while loop: run code until the condition fails

PHP while repeats a block as long as its condition evaluates to true. The condition is checked before each iteration, so the body may never run if the condition starts as false. Use while when the number of iterations depends on a runtime condition — retries, stream reads, or pagination — rather than a known count.

PHP while loop example (retry counter)

Output:

Output will appear here...

Output:

Attempt 1
Attempt 2
Attempt 3
Attempt 4
Done after 4 attempts

How the loop stops

  1. $attempt = 1 initializes the counter variable that drives loop termination.
  2. while ($attempt <= $maxAttempts) checks the condition before each pass. When $attempt exceeds $maxAttempts, the loop stops.
  3. Inside the body, $attempt++ advances the counter. Without this update, the condition would never become false, creating an infinite loop.
  4. After the loop exits, the code after the closing brace runs with $attempt still in scope and equal to 5.

Common Mistakes With PHP while Loops

Forgetting to change the condition state

Wrong:

$i = 0;
while ($i < 3) {
    echo "$i\n";
    // $i++ is missing — infinite loop
}

Right:

$i = 0;
while ($i < 3) {
    echo "$i\n";
    $i++;
}

Using = instead of === in the condition

Wrong:

$isReady = false;
while ($isReady = true) { // assigns true (always truthy)
    break; // prevents an infinite loop in this demo
}

Right:

$isReady = false;
while ($isReady === true) {
    // ...
}

An assignment expression evaluates to the assigned value, so the condition can stay truthy forever. Assignment in a condition is only intentional when you’re capturing a function result (for example, fetch loops).

PHP while vs do-while vs for

Use a PHP do while loop (do...while) when the body must run at least once.

LoopCondition checkBest for
whileBefore each iterationUnknown iteration count, may run zero times
do...whileAfter each iterationMust run at least once (input validation, menus)
forBefore each iterationKnown count with init/increment in one line
foreachN/A (iterates collection)Arrays and Traversable objects

Use while for condition-driven workflows. Switch to for when the loop has a fixed range, and foreach when iterating an array or iterable.

What Is a PHP while Loop?

A PHP while loop is an entry-controlled loop that evaluates a boolean expression before each iteration. If the expression is true, the body executes; if false, control jumps past the closing brace. PHP also supports the alternative syntax while (condition): ... endwhile;, which is common in template files where brace matching is harder to read.

More Examples

Retry until a condition succeeds with a safety cap:

$success = false;
$tries = 0;
while (!$success && $tries < 5) {
    $tries++;
    $success = ($tries === 3); // simulated success on 3rd try
}
echo "Resolved after $tries tries";

Combining two conditions prevents unbounded retries. Always cap retry loops with a maximum to avoid denial-of-service behavior on transient failures.

Using do...while to guarantee one execution:

$input = '';
do {
    $input = 'valid'; // simulated user input
} while ($input === '');
echo $input;

do...while checks the condition after the first pass, so the body always runs at least once — useful for prompts and menu loops.

FAQ

How do you stop a while loop in PHP?

Use break to exit the loop immediately, or change the condition variable so the test becomes false. break 2 exits two nesting levels at once. Avoid relying solely on break for normal termination — update the condition to make the loop’s intent clear.

Does a PHP while loop run if the condition is false?

No. while is an entry-controlled loop: if the condition evaluates to false on the first check, the body never executes. Use do...while when the body must run at least once regardless of the initial condition. This difference matters when “zero iterations” is a valid outcome (empty results, failed reads, or zero attempts).

Can you loop through arrays with while in PHP?

Yes, but avoid each() (removed in PHP 8). For arrays, foreach is the idiomatic choice. If you do need while, track an index and increment it, or use current()/next() when you specifically want pointer semantics.