A loop repeats code. The while loop keeps running its block as long as a condition is true.
<?php
$count = 1;
while ($count <= 3) {
echo "Round $count\n";
$count++;
}
Round 1
Round 2
Round 3
How it works
- PHP checks the condition (
$count <= 3). - If it is true, PHP runs the block, then goes back to step 1.
- If it is false, PHP leaves the loop.
The condition is checked before each round. If it is false from the start, the block never runs.
<?php
$count = 10;
while ($count <= 3) {
echo "This never prints";
}
echo "Skipped the loop";
Skipped the loop
Change something inside the loop
Something inside the loop must eventually make the condition false. In the first example, $count++ does that. If you forget it, the loop never ends. That is an infinite loop, and it makes the script hang until PHP’s time limit stops it.
When while is the right tool
Use while when you do not know how many rounds you need. For example, “keep going until we run out”.
<?php
$money = 100;
$days = 0;
while ($money > 20) {
$money -= 30;
$days++;
}
echo "Money lasted $days days, $money left";
Money lasted 3 days, 10 left
Count down
<?php
$seconds = 3;
while ($seconds > 0) {
echo $seconds . "...\n";
$seconds--;
}
echo "Go!";
3...
2...
1...
Go!
Reading rows one at a time
You will meet while again in the database chapters, where it reads one record at a time until none are left. Here is the same idea with an array.
<?php
$queue = ["Ann", "Bob", "Cy"];
while ($name = array_shift($queue)) {
echo "Serving $name\n";
}
Serving Ann
Serving Bob
Serving Cy
array_shift() removes and returns the first item. When the array is empty it returns null, which stops the loop.
The forgotten update
while, ask: “what makes this stop?”