CodeBlanks Logo Icon CodeBlanks

The while loop

PHP course · Beginner · Lesson 43/116

Learn the while loop that runs as long as a condition holds.

The while loop

The while loop runs as long as a condition is true. The condition is written inside parentheses and checked before each step. When the condition becomes false, the loop ends.

For example, while ($count > 0) runs the body as long as $count is greater than zero. while is a good fit when you do not know in advance how many times to repeat.

The infinite loop risk

A while loop runs as long as its condition is true. If the condition never becomes false, the loop turns into an infinite loop and the program freezes. So the body must change something that affects the condition.

For example, $count = 5; while ($count > 0) { echo $count; } never decreases $count, so the loop never stops. The fix is to add $count--; inside the body.

Exercise Count down from 5 to 1

Use a while loop to print the numbers from 5 down to 1, one per line. Start $count at 5 and decrease it by one each step.

Show example solution
Write while ($count >= 1), then echo $count . "\n" and $count-- inside the body.
Example solution:
<?php
$count = 5;
// Count down from 5 to 1
while ($count >= 1) {
    echo $count . "\n";
    $count--;
}

Test yourself

  1. What is the output of the code below?

    $count = 2;
    while ($count > 0) {
        echo $count;
        $count--;
    }
    • 12
    • 21
    • 2
    • 210
    Show answer

    21 — Correct. It prints 2 then 1, so the output is 21.

  2. Write the while condition

    $count = 5;
    while (____) {
        echo $count;
        $count--;
    }
    Show answer
    $count = 5;
    while ($count >= 1) {
        echo $count;
        $count--;
    }
  3. Match each loop or part to its purpose

    for
    Fixed number of repeats
    while
    While a condition holds
    $i++
    Increases counter by one
  4. What happens if a while condition is false from the start?

    • It runs once
    • It loops forever
    • It throws an error
    • It never runs
    Show answer

    It never runs — Correct. If the condition is false from the start, the body never runs.

All lessons in Beginner