Summary: in this tutorial, you will learn about PHP do-while loop statement to execute a code block repeatedly based on a condition checked at the end of each iteration.
Introduction to PHP do-while loop statement
The PHP do-while
loop statement allows you to execute a block of code repeatedly based on a condition. Unlike the while loop statement whose the condition is checked at the beginning of each iteration, the condition in the PHP do-while
statement is checked at the end of each iteration. It means the loop will execute at least once even the condition is evaluated to false
.
The following illustrates the syntax of the do-while
loop statement:
1 2 3 4 5 | <?php do { // code block to be executed } while (expression); |
The code block inside do-while
loop statement executes first and then expression
is checked at the end of each iteration. If the expression evaluates to true
, the code block executes repeatedly until the expression evaluates to false
.
The following flowchart illustrates the do-while
statement.
while vs. do-while
The differences between the do-while
and while
loop are:
- The code block inside the
do-while
loop body executes at least one whereas the code block inside thewhile
loop body may not execute at all if the expression evaluates tofalse
. - The expression in the
do-while
loop statement is evaluated at the end of each iteration whereas the expression in thewhile
loop statement is evaluated at the beginning of each iteration.
PHP do-while loop statement examples
In the following example, the code block inside the do-while
loop statement executes exactly one time.
1 2 3 4 5 6 | <?php $i = 0; do { echo $i; } while ($i > 0); |
The code inside the loop body executes first to display the variable $i
. Because the value of the $i
is 0 so the condition is met, therefore, the loop stops.
In the following example, the code block inside the do-while
loop executes 10 times:
1 2 3 4 5 6 7 | <?php $i = 10; do { echo $i . '<br/>'; $i--; } while ($i > 0); |
In this tutorial, you have learned how to use PHP do-while
loop statement to execute a code block repeatedly until a condition is met.