PHP do-while Loop

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:

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.

PHP do while loop

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 the while loop body may not execute at all if the expression evaluates to false.
  • The expression in the do-while loop statement is evaluated at the end of each iteration whereas the expression in the while 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.

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:

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.

  • Was this tutorial helpful ?
  • YesNo