The do…while statement will always execute the condition, and repeat the loop while the condition is true.

The main difference from “while loops” is that the first iteration of a do-while loop is guaranteed to run, whereas it’s may not necessarily run with a regular while loop (the truth expression 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);

Example1:
Code:

$i = 0;
do {
    echo $i;
} while ($i > 0);

Output:

0

Example2:
Code:

$i=1;
do
  {
  $i++;
  echo "The number is " .$i . "
"; } while ($i<=5);

Output:

The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

eXTReMe Tracker