ZetCode

PHP do Keyword

last modified November 25, 2026

The PHP do keyword starts a post-test loop: the body runs first, and the condition is checked afterwards. That guarantees at least one iteration, which is exactly what prompts, menus, and retry loops need.

This article covers the syntax, the guaranteed first pass, the difference from while, input validation, repeat-until patterns, break and continue, nesting, and the semicolon that closes the statement.

Basic definitions

A do-while loop has two parts: a body introduced by do, and a condition written after while. PHP runs the body, then evaluates the condition; if the condition is true, the body runs again. The body therefore always runs at least once, even when the condition is false before the first pass.

The syntax is do { ... } while (condition);. The semicolon after the closing parenthesis is part of the statement, not an optional nicety. The condition can be any expression that PHP converts to a boolean, and it is evaluated after every iteration, including the first.

This is the opposite order from a while loop, which tests first and may skip the body entirely. A do-while fits tasks that must happen once before there is anything to test: showing a prompt, drawing a menu, taking a first measurement, or retrying an operation. The while keyword and for keyword articles cover the pre-test loops.

A first do-while loop

The first example counts down from five. The body prints the value and decrements the counter; the condition decides whether another pass is needed.

do_countdown.php
<?php

declare(strict_types=1);

$count = 5;

do {
    echo $count;
    if ($count > 1) {
        echo ", ";
    }
    $count--;
} while ($count > 0);

echo "\n";

The variable starts at 5. Each pass prints the current value, adds a comma unless the value is the last one, and decrements the counter. When $count reaches 0, the condition is false and the loop ends. The separator logic sits inside the body because the comma belongs between the values, not after the last one.

$ php do_countdown.php
5, 4, 3, 2, 1

The body runs before the condition

The difference from a while loop is easiest to see with a counter that starts at zero. Both loops begin with the same value, but only one of them reaches its body.

do_vs_while.php
<?php

declare(strict_types=1);

$tries = 0;

while ($tries > 0) {
    echo "while ran\n";
    $tries--;
}

$tries = 0;

do {
    echo "do ran\n";
    $tries--;
} while ($tries > 0);

echo "tries: $tries\n";

The while loop tests $tries > 0 first. The condition is false, so the body is skipped and nothing is printed. The do-while runs its body once, decrements the counter to -1, and only then tests the condition. The negative value is a useful reminder that the body ran before the first test.

$ php do_vs_while.php
do ran
tries: -1

Validating input

A prompt is a natural do-while: the program has to ask at least once, and it repeats only while the answer is invalid.

do_input.php
<?php

declare(strict_types=1);

$answers = ["abc", "-2", "0", "7"];
$attempt = 0;

do {
    $raw = $answers[$attempt];
    $attempt++;

    $number = filter_var($raw, FILTER_VALIDATE_INT, [
        "options" => ["min_range" => 0, "max_range" => 10],
    ]);

    echo "attempt $attempt: '$raw' is ",
        $number === false ? "invalid" : "valid", "\n";
} while ($number === false);

echo "accepted $number after $attempt attempts\n";

The array stands in for keyboard input so the script runs without a terminal. Each pass takes one answer and validates it as an integer between 0 and 10. filter_var returns the integer or false, and the strict comparison $number === false is important: a loose check such as !$number would reject the valid zero. The loop ends as soon as a valid value appears.

$ php do_input.php
attempt 1: 'abc' is invalid
attempt 2: '-2' is invalid
attempt 3: '0' is valid
accepted 0 after 3 attempts

Repeating until a condition is met

The reverse pattern is to repeat an action until something happens. The number of passes is unknown in advance, and the action has to happen at least once.

do_dice.php
<?php

declare(strict_types=1);

mt_srand(2026);

$rolls = 0;

do {
    $roll = mt_rand(1, 6);
    $rolls++;
    echo "roll $rolls: $roll\n";
} while ($roll !== 6);

echo "finished after $rolls rolls\n";

The seed is fixed only to make the output reproducible; real code would omit mt_srand. The loop rolls a die and stops when the result is 6. A while version would need one roll before the loop and the same roll again inside it, duplicating the statement. The do-while keeps the roll in one place.

$ php do_dice.php
roll 1: 4
roll 2: 1
roll 3: 3
roll 4: 1
roll 5: 4
roll 6: 6
finished after 6 rolls

break and continue

The loop control statements work inside a do-while as they do in other loops, with one timing detail for continue.

do_break_continue.php
<?php

declare(strict_types=1);

$n = 0;

do {
    $n++;

    if ($n % 2 === 0) {
        continue;
    }

    echo $n;

    if ($n < 9) {
        echo " ";
    }

    if ($n >= 9) {
        break;
    }
} while (true);

echo "\ndone at $n\n";

Even numbers are skipped, and the loop stops after printing 9. continue in a do-while jumps to the condition test, not to the first line of the body. The increment is written before the test, so progress is preserved. If the increment came after continue in a loop with a normal condition, an even value would stay unchanged and the condition would send the loop back to the same state forever. The always-true condition makes the exit depend entirely on break.

$ php do_break_continue.php
1 3 5 7 9
done at 9

Nested loops

A do-while can contain another do-while. The inner loop finishes its own sequence before the outer loop advances.

do_nested.php
<?php

declare(strict_types=1);

$row = 1;

do {
    $col = 1;

    do {
        echo $row * $col;
        if ($col < 3) {
            echo "\t";
        }
        $col++;
    } while ($col <= 3);

    echo "\n";
    $row++;
} while ($row <= 3);

The outer loop walks the rows and the inner loop walks the columns, printing a 3 by 3 multiplication table. The tab separates the columns; a browser would need a table or CSS because runs of whitespace collapse in HTML. Nesting adds a second condition to maintain, so keep the inner body short.

$ php do_nested.php
1	2	3
2	4	6
3	6	9

The trailing semicolon

The most common do-while syntax error is a missing semicolon after the condition. Unlike a while loop header, the do-while ends with a semicolon.

do_semicolon.php
<?php

declare(strict_types=1);

$n = 0;

do {
    $n++;
} while ($n < 3)

echo $n, "\n";

PHP reports a parse error at the next token, here echo, because it is still waiting for the semicolon that closes the statement. The reported line points at the following statement, not at the line where the semicolon is missing, which is why the message can look misplaced.

$ php do_semicolon.php
Parse error: syntax error, unexpected token "echo", expecting ";" in /app/do_semicolon.php on line 11

Best practices

A do-while is a promise that the body is safe to run before anything is known. Keep that promise visible.

Source

PHP manual: do-while

PHP manual: while

PHP manual: break and continue

This article covered the PHP do keyword: the post-test loop, its guaranteed first iteration, input validation, repeat-until patterns, break and continue, nesting, and the required semicolon. Continue with PHP while loop for the pre-test form, or read PHP for loop and PHP break keyword for the other loop controls.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all PHP tutorials.