PHP Do While Loop

The do...while loop is a PHP construct that executes a block of code at least once before checking the specified condition. It will continue repeating the loop as long as the condition remains true.

Tutorials dojo strip



Example: Counting Cars

Here’s an example where we count the number of cars in a lot, as long as the count remains under 6:

$carCount = 1;

do {
  echo $carCount;
  $carCount++;
} while ($carCount < 6);

Note: Since the condition is evaluated after the code block, this loop will always execute at least once, even if the condition is false.




Executing Once When Condition is False

If the initial condition is not met, the do...while loop still runs the code block once before stopping.

Example: Cars Starting at an Invalid Count

Let’s set the car count to 8 and see the result:

$carCount = 8;

do {
  echo $carCount;
  $carCount++;
} while ($carCount < 6);

Here, the code executes once even though the condition ($carCount < 6) is false.




The break Statement

The break keyword is used to terminate the loop prematurely, even if the condition evaluates to true.

Example: Stop at a Specific Motorcycle Count

Terminate the loop when the motorcycle count reaches 3:

$motorcycleCount = 1;

do {
  if ($motorcycleCount == 3) break;
  echo $motorcycleCount;
  $motorcycleCount++;
} while ($motorcycleCount < 6);




The continue Statement

The continue keyword skips the current iteration and moves on to the next one.

Example: Skip Certain Cars

Skip displaying the car count if it equals 3:

$carIndex = 0;

do {
  $carIndex++;
  if ($carIndex == 3) continue;
  echo $carIndex;
} while ($carIndex < 6);
Tutorials dojo strip
Scroll to Top