PHP do-while Loop

Updated: April 20th, 2022, 08:07:32 IST
Published: April 20th, 2022
PHP do-while Loop
Title: PHP do-while Loop

do-while loops are very similar to while loops, except the true condition is checked at the end of each iteration instead of in the beginning. The do...while loop executes through a block of code at-least once, and then repeats the loop as long as the specified condition is true.

PHP do-while Loop

The main difference between do-while loops and regular while loops is that the first iteration of a do-while loop is guaranteed to run at-least once (the truth expression is only checked at the end of the iteration), whereas the first iteration of a regular while loop may or may not run (the true expression / condition is checked at the beginning of each iteration, if it evaluates to false right from the beginning, the loop execution would end immediately).

Syntax

do {
  code to be executed;
} while (condition is true);

Note: In a do...while loop, the condition is tested AFTER the statements within the loop has to be executed at first. This implies that even if the condition is false, the do...while loop will execute its statements at least once. Consider the following example.

This example sets the $n variable to 10, then it runs the loop, and then the condition is checked:

Example #1

<?php
$n = 10;

do {
  echo "The number is: $n <br>";
  $n++;
} while ($n <= 10);
?>