PHP do-while Loop

The do...while loop in PHP, is used when we need to execute some block of code for at least once, then need to continue the execution of same block of code, until the specified condition evaluates to be false. For example:

<?php
   $x = 1;
   do{
      echo $x, "<BR>";
      $x++;
   }while($x<=10);
?>

The snapshot given below shows the sample output produced by above PHP example:

php do while loop

PHP do-while Loop Syntax

The syntax of do...while loop in PHP, is:

do{
   block of code;
}while(condition);

First the block of code; gets executed, then the condition expression gets evaluated. If the condition evaluates to be true, then the block of code; again gets executed. This process continues, until the condition evaluates to be false.

PHP do-while Loop Example

As already told, if the condition evaluates to be false at first run, then in that case too, the block of code; will be executed for once. For example:

<?php
   $x = 10;
   do{
      echo "<p>The value of \$x is $x</p>";
      $x--;
   }while($x<5);
?>

The output should be The value of $x is 10. That is, only once, the statements inside the body of the loop, has been executed.

PHP Online Test


« Previous Tutorial Next Tutorial »