do-while loop in PHP with examples

The "do-while" loop in PHP is used when we need to execute a block of code at least once and then continue the execution of the same block of code until the specified condition evaluates to be false.

PHP do-while loop syntax

In PHP, the syntax of a do-while loop 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 true, then the "block of code" again gets executed. This process continues until the condition is evaluated as false. For example:

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

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

php do while loop

The above PHP code starts by giving the value 1 to a variable called $x.

Then it goes into a "do-while" loop, which first runs the code in the "do" block and then checks the loop condition (in this case, whether $x is less than or equal to 10).

Inside the "do" block, the echo statement sends out the current value of $x and a line break. Then, the increment operator ($x++) is used to add 1 to the value of $x.

The loop keeps going as long as the "while" statement's condition is true. This means that it will keep printing the value of $x and adding one to it until it reaches 10.

PHP do-while loop example

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

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

The PHP code displayed above assigns the value 10 to the variable $x. The program then enters a "do-while" loop, which executes the code within the "do" block before checking the loop condition (in this case, whether $x is less than 5).

Within the "do" block, the code uses string interpolation to echo a paragraph containing the current value of $x ("The value of \$x is $x"), where the backslash is used to escape the $ symbol.

The value of $x is then decreased by 1 using the decrement operator ($x--).

The loop will continue to iterate until the "while" statement's condition is met, which means it will continue to print the paragraph with the current value of $x and decrement it until it reaches a value less than 5.

However, because the initial value of $x is greater than 5, the condition in the "while" statement is initially false, so the loop will execute only once. Consequently, the output of the code will be a single paragraph with $x equal to 10. Or we can say that the output should be The value of $x is 10. That is, only once have the statements inside the body of the loop been executed.

Advantages of the do-while loop in PHP

Disadvantages of the do-while loop in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!