Skip to main content

The PHP do...while Loop

A do...while loop always runs its code at least one time. After that first run, it checks the condition and goes round again for as long as the condition stays true.

Note: The reason for this behavior is that the test sits at the bottom of the loop, after the code. Even a condition that is false from the start cannot stop the first run.

Do while loop basics

$i starts at 1, and the loop prints it and adds 1 until $i is no longer below 6:

Prompt
Write a PHP script that sets $i to 1. Use a do...while loop to echo $i and increment $i by 1, as long as $i is less than 6.
Output: PHP script

Do while with false condition

Here $i starts at 8, which already fails the test $i < 6. The value still gets printed once, since PHP only looks at the condition after the code block has run:

Prompt
Write a PHP script that sets $i to 8. Use a do...while loop to echo $i and increment $i by 1, as long as $i is less than 6. The loop should still execute once.
Output: PHP script

Do while syntax

The general form looks like this, with the condition written after the closing brace:

index.php
do {
  // code to be executed
} while (condition);

The PHP break Statement

The break statement ends a do...while loop early, whether or not its condition is still true.

Stop the loop with break

Printing stops when $i reaches 3, so only 1 and 2 appear:

Prompt
Write a PHP script that sets $i to 1. Use a do...while loop with condition $i < 6. Inside the loop, if $i equals 3, use break to stop. Otherwise echo $i and increment $i.
Output: PHP script

The PHP continue Statement

To leave out a single pass, use continue. The rest of that iteration is dropped, and the loop carries on with the following one.

Skip iteration with continue

Notice that $i is increased at the top of the body, before the check. When it equals 3 the echo is skipped, so 3 is missing from the output:

Prompt
Write a PHP script that sets $i to 0. Use a do...while loop with condition $i < 6. Inside the loop, increment $i first. If $i equals 3, use continue to skip the echo. Otherwise echo $i.
Output: PHP script