The do...while loop is a variant of while
loop. It evaluates the condition at the end of each loop iteration. Thus, a do-while loop the block of code is executed once before the condition is evaluated (this is its difference from the while loop). If the condition is true, the block of code is repeated as long as the specified condition is true.
The following is the syntax for the PHP do
...while
loop.
do {
code to be executed;
} while (condition is true);
Below is an example of a do
...while
loop in PHP.
<?php
$i = 1;
do {
echo $i . "<br>";
$i++;
} while ($i <= 10);
Here is another example of the do
...while
loop where the condition is already false from the start:
<?php
$i = 1;
do {
echo $i . "<br>";
$i++;
} while ($i > 10);
Exercise
Using the do
...while
print the numbers from 5 to 1 (decreasing order).
<?php
$var = 123;
<?php
$i = 5;
do {
echo $i . "<br>";
$i--;
} while ($i >= 1);
{
"test_output_contains":[
{
"expected":"5",
"error_message":"Sorry. Please try again."
},
{
"expected":"4",
"error_message":"Sorry. Please try again."
},
{
"expected":"3",
"error_message":"Sorry. Please try again."
},
{
"expected":"2",
"error_message":"Sorry. Please try again."
},
{
"expected":"1",
"error_message":"Sorry. Please try again."
}
],
"success_message":"Good job!",
"error_message":"Please read the instructions again."
}