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.
$i = 10; do { echo $i, "\n"; } while ($i < 5); // prints 10 once
Try it
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.
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
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. Choosedo-whilewhen the first pass must happen before you can test anything (for example, extracting digits of0should 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
whileloop. The second example uses$okthat way. continuejumps to the condition check, not back to the top of the body.breakleaves 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,forandforeach. Usedo-whilewhere it reads naturally. - No colon syntax. There is no
enddo; use braces.
Related
while,for,foreach,break and continue- Lessons: Loops, Break and continue