PHP do while loop

      No Comments on PHP do while loop

A PHP do while loop, loops through a block of code once, and then repeats the loop as long as the specified condition is true.

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

The do…while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

PHP do while loop


         $i = 0;
         do {
         while( $i < 6 );
         echo ("Loop ended at i = $i" );

Result of the above code :

Loop ended at i=6

The above code executes as follows:
At $i=0, the loop runs for the first time before checking the while condition and calculates $i=1. The at exit point the loop evaluates the while condition. Here $i=1<6, which evaluate while condition to true. The loop controls again executes the loop. This goes on till the while evaluates to false.

Fact about PHP do while loop

It is should be noted that there is no alternative syntax to PHP do while as it is there for while loop.

while ($a < 10) :

But this won’t work:

do :
while ($a <= 10);

Another Example:

    do {  
    echo "Increment Number : $x <br />";  
    echo "Hello World"; 
    }while ($x<5)  


Increment Number : 0
Hello World
Increment Number : 1
Hello World
Increment Number : 2
Hello World
Increment Number : 3
Hello World
Increment Number : 4
Hello World
Increment Number : 5
Hello World

More about do while

do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it 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).

Leave a Reply

Your email address will not be published. Required fields are marked *