PHP do…while
Summary: in this tutorial, you will learn how to use the PHP do...while
loop statement to execute a code block repeatedly.
Introduction to PHP do…while loop statement
The PHP do...while
statement allows you to execute a code block repeatedly based on a Boolean expression. Here’s the syntax of the PHP do-while
statement:
do {
statement;
} while (expression);
Code language: HTML, XML (xml)
Unlike the while
statement, PHP evaluates the expression
at the end of each iteration. It means that the loop always executes at least once, even the expression
is false
before the loop enters.
The following flowchart illustrates how the do...while
statement works:
do…while vs. while
The differences between the do...while
and while
statements are:
- PHP executes the statement in
do...while
at least once, whereas it won’t execute thestatement
in thewhile
statement if theexpression
isfalse
. - PHP evaluates the
expression
in thedo...while
statement at the end of each iteration. Conversely, PHP evaluates theexpression
in thewhile
statement at the beginning of each iteration.
PHP do…while loop statement example
In the following example, the code block inside the do...while
loop statement executes precisely one time.
$i = 0;
do {
echo $i;
} while ($i > 0);
Code language: HTML, XML (xml)
The code inside the loop body executes first to display the variable $i
. Because the value of the $i
is 0, the condition is met, the loop stops.
In the following example, the code block inside the do...while
loop executes ten times:
$i = 10;
do {
echo $i . '<br>';
i--;
} while ($i > 0);
Code language: HTML, XML (xml)
In this tutorial, you have learned how to use PHP do...while
loop statement to execute a code block repeatedly until a condition is false
.