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:

PHP

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:

PHP

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:

PHP

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:

PHP
Tutorials dojo strip