Skip to content
Tutorials Center
My learning

Topics

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.

PHP
$n = 1;
while ($n <= 3) {
    echo $n++, " ";
}

Try it

PHP Counting and halving

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 Reading until a condition, with break

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
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-while when 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 by max_execution_time.
  • Assignment in the condition (while ($row = next_row())) is common, but a falsy value such as 0 or "" also ends the loop. Compare explicitly (!== false) when those values are valid data.
  • break and continue. break leaves the loop; continue jumps to the next condition check. See break and continue.
  • Prefer foreach for arrays. It is shorter and cannot go out of range; see foreach. Prefer for when you have a counter.
  • Infinite loops on purpose. while (true) with a break inside 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.