I'll keep the donut theme as we move on to do-while loops. Do-while loops start with the keyword DO and conclude with the keyword WHILE followed by the conditional expression. Between DO and WHILE exists the braced set of loop code.
<?php $remaining_donuts = 12; do { echo "I'm eating a donut...>br /<"; $remaining_donuts--; } while ($remaining_donuts > 0); echo "I ate them all!\n"; ?>
TThe output of this example is the same as the first while loop example shown earlier. 12 is assigned to the variable $remaining_donuts. For each donut consumed a message is outputted and $remaining_donuts is decremented. The code block is no longer processed once the value of the conditional resolves false. A concluding "I ate them all!" message is outputted.
The core difference between the do-while and the while loop is when the conditional expression is evaluated. Do-while loops do not evaluate the expression until after executing the code block at least once. The flow of the script falls into the braced code and then tests if it should repeat the section again.
A do-while loop on the other hand will process its code bock at least once, as lustrated with the following code:
<?php $remaining_donuts = -1; do { echo "I'm eating a donut...<br />"; $remaining_donuts--; } while ($remaining_donuts > 0); echo "I ate them all!"; ?>
Even though the value of $remaining_donuts has been set to a negative value, our hungry program still manages to find something to eat before admitting it's gluttony!
When to use a do-while loop or a while loop depends on the logic of your code... If code may or may not be looped depending on a condition, you should use a while loop because its conditional expression is tested first. If code must be executed at least once but future loops are then dependent on the evaluation of a conditional expression, use a do-while loop because the expression is tested after the first execution.