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:

<?php 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 the statement in the while statement if the expression is false.
  • PHP evaluates the expression in the do...while statement at the end of each iteration. Conversely, PHP evaluates the expression in the while 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 exactly one time.

<?php $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 10 times:

<?php $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.

Did you find this tutorial useful?