PHP Do While

The Do While statement will loop a block of code until the condition becomes false. It is similar to the while loop, except the expression goes at the bottom so the code will execute at least once.



$w = 15;

do {


echo '<li>'.'My number is '.$w.'</li>';

} while ($w < 150);


Code explained:

  • Declare a variable
  • Then increment $w if it is less than 150 (the While Statement)
  • Print out the result
  • Also, notice this is in a ul tag

Breaking from Loops

Similar to the While Statement, you can also break from loops when a certain condition has been reached.


$w = 1;


       if ($w == 250){
       echo "<li> $w </li>";
}while ($w < 300)

This is similar to the above example except we have an If Statement which checks to see if w is equal to 250, and if it is it will break from the loop (in other words it will end incrementing). You can try this below by choosing a number.

Try It!

Choose a number: