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:
- Initialization: set up the state the condition reads, before the loop starts.
- Condition: an expression PHP evaluates before each iteration.
- 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.
$i = 1;
while ($i <= 3) {
echo $i . "\n";
$i++;
}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.
$count = 5;
while ($count < 3) {
echo "never runs\n";
}
echo "done\n";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.
$balance = 100;
$months = 0;
while ($balance > 0) {
$balance -= 30;
$months++;
}
echo json_encode(["months" => $months, "balance" => $balance]);{"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
$jwhen the condition reads$ihas 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().
0has one digit.- Negative numbers ignore the sign, so
-450has 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
whileloop 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.
Conditionals
- Initialize a loop counter
- Update loop state so iteration terminates