Do While Loop

The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.

 

Syntax:

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

 

Note: In a do...while loop the condition is tested AFTER executing the statements within the loop. This means that the do...while loop will execute its statements at least once, even if the condition is false. See example below.

 

Example:

<?php
  $i = 0;
  $num = 0;

  do {
    echo "The number is: $i <br>";
    $i++;
  }

  while( $i < 10 );
  echo ("<br><br>");
  echo ("Loop stopped at i = $i");
?>

 

Output:

The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9


Loop stopped at i = 10

 

Explanation: The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10.