PHP do while Loops

A slight variation to the while loop is the do … while loop, used when you want a block of code to be executed at least once and made conditional only after that. Example 4-31 shows a modified version of the code for the 12 times table that uses such a loop.

Example 4-31. A do … while loop for printing the times’ table for 12
<?php
$count = 1;
do
echo "$count times 12 is " . $count * 12 . "<br>";
while (++$count <= 12);
?>

Notice how we are back to initializing $count to 1 (rather than 0) because the code is being executed immediately, without an opportunity to increment the variable. Other than that, though, the code looks pretty similar. Of course, if you have more than a single statement inside a do … while loop, remember to use curly braces, as in Example 4-32.

Example 4-32. Expanding Example 4-31 to use curly braces
<?php
$count = 1;
do {
echo "$count times 12 is " . $count * 12;
echo "<br>";
} while (++$count <= 12);
?>
Few more examples of do while loop:
<?php
do {
    if ($i < 5) {
        echo "i is not big enough";
        break;
    }
    $i *= $factor;
    if ($i < $minimum_limit) {
        break;
    }
   echo "i is ok";

    /* process i */

} while (0);
?>

 

<< Prev Next >>

Loading