The do ... while loop takes an expression such as a while statement but places it at the end. The syntax is:
code to execute; } while (expression);
This loop is useful when you want to execute a block of code at least once regardless of the expression value. For example, let's count to 10 with this loop, as shown in Example 4-15.
Example 4-15. Counting to 10 with do ... while <?php
echo "Number is ".$num."<br />"; $num++; } while ($num <= 10);
Example 4-15 produces the same results as Example 4-14; if you change the value of $num to 11, the loop processes differently:
This produces: 11
The code in the loop displays 11 because the loop always executes at least once. Following the pass, while evaluates to FALSE, causing execution to drop out of the do ... while loop.
Was this article helpful?