PHP While Loop

A while loop runs its body repeatedly for as long as a condition evaluates to true, checking that condition before every single pass.

How the while loop works

The while loop is the simplest loop in PHP. It tests a condition first; if the condition is true, it runs the block of code, then goes back and tests the condition again. This repeats until the condition finally turns false, at which point PHP moves on to whatever comes after the loop. Because the test happens before the body, a while loop can run zero times if the condition is false from the start.

Counting up with while

<?php
$number = 1;
while ($number <= 5) {
    echo "Number: $number\n";
    $number++;
}
?>

In the example above the loop prints the numbers 1 through 5. The variable $number starts at 1, and the line $number++ adds one on each pass. Once $number reaches 6 the test $number <= 5 becomes false and the loop ends. Forgetting that increment is the classic beginner mistake, and it produces a loop that never stops.

  • Set up your control variable before the loop begins.
  • Write a condition that will eventually become false.
  • Change the control variable inside the body so the loop makes progress.
  • Remember the body may not run at all if the condition starts out false.

When to choose while

Reach for while when you do not know in advance how many times the loop should run. A common case is reading data until you hit the end, or repeating a process until some target is met. The example below halves a number until it drops below one, and there is no fixed count of passes decided up front.

Looping until a condition is met

<?php
$value = 100;
while ($value >= 1) {
    echo "Value is now $value\n";
    $value = $value / 2;
}
echo "Loop finished.\n";
?>
Note: You can leave a while loop early with the break statement, or skip to the next pass with continue. This is handy when a special condition comes up partway through the body.
Featurewhile loop
Condition checkedBefore each pass
Minimum runsZero
Best forUnknown number of repetitions
Counter requiredNo, any true/false test works

If you find that you always want the body to run at least once regardless of the condition, the do...while loop on the next page is a better fit.