PHP Reference ยท Language Constructs and Statements
PHP while loop
Reference for the PHP while loop: repeat code while a condition stays true, avoiding infinite loops, reading until a sentinel, and alternative syntax.
while repeats a block of code as long as its condition is truthy. The condition is checked before every iteration, so the body may run zero times. Use it when you do not know in advance how many repetitions you need: reading lines until the end of input, waiting for a state to change, or walking a structure until you reach its end.
Make sure something inside the loop eventually makes the condition false, or the loop never ends.
$n = 1; while ($n <= 3) { echo $n++, " "; }
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
while (condition) { // body } while (condition): // body endwhile;
| Name | Description |
|---|---|
condition |
Any expression, converted to bool before each pass. The loop ends when it is falsy. |
Return value: none; while is a statement.
Usage notes
- Zero or more runs. If the condition is false at the start, the body never executes. Use
do-whilewhen you need at least one run. - Update the loop variable. Forgetting
$i++is the classic infinite loop. A CLI script can be stopped with Ctrl+C; a web request is stopped bymax_execution_time. - Assignment in the condition (
while ($row = next_row())) is common, but a falsy value such as0or""also ends the loop. Compare explicitly (!== false) when those values are valid data. breakandcontinue.breakleaves the loop;continuejumps to the next condition check. See break and continue.- Prefer
foreachfor arrays. It is shorter and cannot go out of range; seeforeach. Preferforwhen you have a counter. - Infinite loops on purpose.
while (true)with abreakinside is fine for event loops and retry logic. - Recomputing the condition.
count($a)in the condition is evaluated each time; store it in a variable if the array does not change and the array is large.
Related
do-while,for,foreach,break and continue- Lessons: Loops, Alternative syntax