Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Language Constructs and Statements

PHP do-while loop

Reference for the PHP do-while loop: run a block at least once and repeat while a condition holds, with examples, the trailing semicolon and pitfalls.

do-while is the loop that checks its condition after each pass. The body therefore always runs at least once, even if the condition is false from the start. That makes it a good fit for "try, then decide whether to try again" logic: retrying an operation, showing a menu, or generating a value until it is acceptable.

There is no alternative colon syntax for do-while, and the statement ends with a semicolon after the condition.

PHP
$i = 10;
do {
    echo $i, "\n";
} while ($i < 5);   // prints 10 once

Try it

PHP At least one run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Retry until success

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
do {
    // body
} while (condition);
Name Description
condition Any expression, converted to bool after each pass. The loop repeats while it is truthy.

Return value: none; do-while is a statement.

Usage notes

  • Runs at least once. This is the only difference from while. Choose do-while when the first pass must happen before you can test anything (for example, extracting digits of 0 should still yield one digit).
  • Do not forget the semicolon after while (condition).
  • Variables created in the body can be used in the condition, which is awkward with a normal while loop. The second example uses $ok that way.
  • continue jumps to the condition check, not back to the top of the body. break leaves the loop. See break and continue.
  • Infinite loops are possible exactly as with while: make sure the state changes.
  • Rarely needed. Most PHP code uses while, for and foreach. Use do-while where it reads naturally.
  • No colon syntax. There is no enddo; use braces.