PHP — While loops
A PHP while loop tests its condition before each pass. If the first test is false, the body runs zero times. A counter that starts at 1 and increases after each print can display 1, 2 and 3.
A simple example
Print while the number is at most 3
- Start with n starts at 1
- Do this Print n, add 1
- Result Stop at 4
<?php
$n = 1;
while ($n <= 3) {
echo $n, PHP_EOL;
$n++;
}
1 2 3
Pack whole batches from stock
Count complete batches of five items by repeatedly removing five while enough stock remains. Keep the leftover units for the next order. Subtracting five on each pass eventually makes the test false. A zero batch size in a generalized version would fail to make progress, so validate it before entering the loop.
The canteen has 17 apples and packs five in each bag. Check the remaining pile before filling each bag. Three full bags leave two apples for the next delivery.
Run the example
Use PHP 8.2 or later. Run these commands from the directory containing the example.
php lesson.php
<?php
declare(strict_types=1);
$stock = 17;
$batches = 0;
while ($stock >= 5) {
$stock -= 5;
++$batches;
}
printf("%d batches, %d left\n", $batches, $stock);
3 batches, 2 left
Seventeen items shrink to 12, 7, then 2. The condition is tested again at 2 and the body stops after three batches.
Try it yourself
What happens with four items? What about exactly five?
Check your answer
Four items yield zero batches and four leftovers. Five items yield one batch and no leftovers because the comparison includes equality.