Do-While Loops
The do...while statement loops through a block of code as long as a specified
condition is evaluated as true. In other words, the while statement will execute
a block of code if and as long as a condition is true.
The do...while loop is similar in nature to the while loop discussed
in the previous section. The key difference is that the do...while loop
body is guaranteed to run at least once. This is possible because the condition
statement is evaluated at the end of the loop statement after the loop body is performed.
The basic do...while loop syntax is shown below:
do {
code to be executed;
} while (condition);
The code within a while loop will repeatedly execute as long as the condition at the end of the loop evaluates to true. The code block associated with the while statement is always enclosed within the { opening and } closing brace symbols.
The following example demonstrates a while loop that continues to execute as long as the variable $number is greater than or equal to 2:
$number = 5;
do {
echo $number . "<br/>";
$number -= 1;
} while ($number >= 2);
In the above example, the variable $number
is initialized to 5. The do...while
loop executes as long as the condition, ($number
>=2), or $number
is greater than or equal to 2, printing the value of $number
to the browser
window. At the end of the loop block, the value of $number
is decreased by 1.
Below is the output generated by the sample loop:
5
4
3
2
During the first run, the value of $number
is equal to 5.
Since the condition of the loop is not checked until after the loop has run once, the
value of $number
, 5 is displayed. Next, the value
of $number
is decremented by 1, becoming 4. Since 4
is greater than 2, the loop runs again and during the second iteration the echo
statement is used to display the value 4. A <br> is concatenated to the display
to create a carriage return each time the loop is processed. This process continues
while the value of $number is 3 and 2. When
$number
is equal to 2, the echo statement displays
the value 2 and the value of $number
is then
decremented to 1. Since 1 is not greater than or equal to 2, the condition is no
longer true and the while loop ends.