PHP While Loop
A while loop repeats a block of code while its test stays true. PHP also has a do-while loop, and that form runs its block once before its first test.
Counting up with while
The counter starts at 1. Each round prints the counter and adds 1 to it.
<?php
$i = 1;
while ($i <= 3) {
echo $i . "\n";
$i++;
}Counting down with while
The counter starts at 3. Each round prints the counter and takes 1 away from it.
<?php
$i = 3;
while ($i >= 1) {
echo $i . "\n";
$i--;
}A do-while loop runs once
The counter holds 10, so the test is false from the start. The block still prints its one line.
<?php
$i = 10;
do {
echo $i . "\n";
} while ($i < 5);Example
<?php
$i = 1;
while ($i <= 3) {
echo 3 * $i . "\n";
$i++;
}Key points
- A while loop tests its condition before each round.
- The block runs again and again while the test stays true.
- A counter often changes inside the block so the test can turn false.
- A do-while loop writes its block before its while test.
- A do-while loop tests at the end, so the block runs at least once.
In this example, the counter starts at 1. The first round prints 3 times 1, which is 3. The next rounds print 6 and 9, and the counter then ends the loop.
Note
A test that never turns false makes a loop run without end.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A do-while loop has a test that is false from the start. How many times does its block run?