PHP - Do...while loop

Introduction

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.

Demo

<?php
     echo "with while: "; 
     $i = 1; /*from   w w w .  j a va  2s. co m*/
     while ($i < 0) { 
        echo $i . " "; 
        $i++; 
     } 
     echo "with do-while: "; 
     $i = 1; 
     do { 
        echo $i . " "; 
        $i++; 
     } while ($i < 0); 
?>

Result

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