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.

Example

<ul>
<?php

$w = 15;

do {

$w++;

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

} while ($w < 150);

?>
</ul>

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.

<ul>
<?php

$w = 1;

do{   

    $w++;
       if ($w == 250){
            break;
        }else{
       echo "<li> $w </li>";
        }
}while ($w < 300)
?>
</ul>

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: