PHP Manual
Prev | Chapter 11. Control Structures | Next

# `while`

`while` loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a `while` statement is:

      1
      2 while (expr) statement
      3

The meaning of a `while` statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the `while` expression evaluates to `TRUE`. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the `while` expression evaluates to `FALSE` from the very beginning, the nested statement(s) won't even be run once.

Like with the `if` statement, you can group multiple statements within the same `while` loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

      1
      2 while (expr): statement ... endwhile;
      3

The following examples are identical, and both print numbers from 1 to 10:

      1
      2 /* example 1 */
      3
      4 $i = 1;
      5 while ($i <= 10) {
      6     print $i++;  /* the printed value would be
      7                     $i before the increment
      8                     (post-increment) */
      9 }
     10
     11 /* example 2 */
     12
     13 $i = 1;
     14 while ($i <= 10):
     15     print $i;
     16     $i++;
     17 endwhile;
     18

Prev | Home | Next
Alternative syntax for control structures | Up | `do..while`