PHP - Do...while loop


The do...while loop is very similar to while.

It evaluates an expression each time, and will execute the block of code until that expression is false.

do...while evaluates the expression after it executes its block of code, so even if the expression is false from the very beginning, the loop will be executed at least once.


     echo "with while: "; 
     $i = 1; //from  ww  w  .ja va 2s . c  o  m
     while ($i < 0) { 
        echo $i . " "; 
     echo "with do-while: "; 
     $i = 1; 
     do { 
        echo $i . " "; 
     } while ($i < 0); 


Here, the code defines two loops with the same expression and block of code, but if you execute them, you will see that only the code inside the do...while is executed.

Related Topics