Lesson 11 of 100
Loops12 min5 checksPHP 8.5

while Loops

Learn how a while loop checks a condition before every iteration, how to initialize and update loop state, and how to avoid loops that never end.

01 · THE IDEAREAD → TRY → LEARN

Repeating work while something is true

A while loop runs a block of code again and again for as long as its condition evaluates to true. The basic shape is while (condition) { ... }. Use it when you do not know in advance how many repetitions you need, or when the stopping rule is easier to express as a condition than as a fixed count.

Every well-behaved while loop has three parts:

  1. Initialization: set up the state the condition reads, before the loop starts.
  2. Condition: an expression PHP evaluates before each iteration.
  3. Update: a statement inside the body that moves the state toward making the condition false.

If you forget the update, the condition never changes and the loop never ends.

A first loop

Here the counter starts at 1, the condition is $i <= 3, and the body ends by incrementing $i.

Example
<?php
$i = 1;
while ($i <= 3) {
    echo $i . "\n";
    $i++;
}
Output
1
2
3

The loop prints 1, 2 and 3. When $i becomes 4 the condition is false, so PHP skips the body and continues after the loop.

The condition is checked first

PHP tests the condition at the beginning of every iteration. If it is false on the very first check, the body never runs at all. This differs from loops that always run once before testing.

Example
<?php
$count = 5;
while ($count < 3) {
    echo "never runs\n";
}
echo "done\n";
Output
done

Because the check happens only at the start of an iteration, changing a variable in the middle of the body does not stop the current pass. The rest of the body still executes; the new value is only noticed on the next check.

A worked example: loop until a target is reached

Suppose a balance of 100 drops by 30 each month, and we want to know how many months pass until it is no longer positive. We do not know the count up front, so while fits well.

Example
<?php
$balance = 100;
$months = 0;
while ($balance > 0) {
    $balance -= 30;
    $months++;
}
echo json_encode(["months" => $months, "balance" => $balance]);
Output
{"months":4,"balance":-20}

Trace it: the balance goes 100, 70, 40, 10, then -20. After four subtractions the condition $balance > 0 is false. Notice that the final balance is below zero, because the check happens only before each pass, not in the middle of one. Tracing a loop by hand like this is the best way to confirm your initialization, condition and update agree with each other.

Common mistakes

  • Missing update. If nothing in the body changes the variables used by the condition, you get an infinite loop. Always ask what changes each time around.
  • Updating the wrong variable. Incrementing $j when the condition reads $i has the same effect as no update.
  • Off-by-one boundaries. Using < versus <= changes how many times the body runs. Test the first and last values.
  • Forgetting the zero case. A loop such as while ($n > 0) skips entirely for 0, which may or may not be the answer you want.

Other forms worth knowing

PHP also allows the alternate syntax while (condition): ... endwhile;, which behaves identically to the braces form. Inside a loop, break leaves immediately and continue jumps to the next condition check. Be careful with continue: if the update statement comes after it, skipping it can create an infinite loop.

The post-increment expression $i++ yields the old value and then increases $i, so echo $i++ prints the value before the change. Beginners often find a separate $i++; line easier to read.

Exercise contract

Write a function countDigits(int $n): int that returns how many decimal digits the integer has, using a while loop and integer division with intdiv().

  • 0 has one digit.
  • Negative numbers ignore the sign, so -450 has 3 digits.
  • Return an integer.

Start with the absolute value, begin the count at 1, and keep dividing by 10 while more than one digit remains. The loop state is the shrinking number, and each pass must reduce it so the loop terminates.

Recap

  • A while loop repeats as long as its condition is true, checked before each iteration.
  • Initialize state before the loop and update it inside the body.
  • A false condition at the start means zero iterations.
  • Trace boundary values by hand to catch off-by-one errors and infinite loops.
Before you start

Conditionals

You’ll practice
  • Initialize a loop counter
  • Update loop state so iteration terminates
Your task

Make countDigits() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.