Do – While loop: do what why?

Do – while loops are principly designed to reduce code duplication. They enable you to do one thing whilst doing something else.

Imagine a coffee shop… orders are taken constantly by the cashier they are then processed by the barista. It’s a repetitive process just like a loop.

Now… what happens if there is no coffee to sell at the start of their shift? Or what happens if you run out during the shift? The whole process could come to a grinding halt (no pun intended!!). If you at least check once you will be ok and during the process even better!

If this was a computerised process the program would always check if the coffee was available even if the cashier part of the app had finished taking the cash for the coffees. You can then take action and keep customers happy either at the beginning of the process, when the shift starts, or during when the stock is flagged as low.

How do they work?

Quite simply they always iterate at least once no matter if the condition is met or not.

Let’s use our coffee example:

//Declare a variable
$coffeeStock = 10;

//Set and test condition

do
  {
    $coffeeStock--;
    if($coffeeStock <= 4)
    {
      echo "You need to order more coffee!";
    }
    echo "Coffee level is " . $coffeeStock . "
"; } while ($i >=0);

What’s happening?

We allocate a variable to store the stock level. Using the DO we make an initial check that we have stock. If we don’t we alert the user that stock is low if less than or equal to four. Try it yourself but this time set the stock level to minus and see what happens… It will always run or DO once.

What is a good use case for a do/while loop?

Imagine if you are checking a shopping cart of products. You will want to check if the orders chosen are in stock. Therefore why not DO a stock check WHILE processing orders.

You could do this another way and call a function at the beginning and end of order and during for that matter. But in this instance you are checking at the start of the loop and during all in one unit of code – no extra function calls required!