30.2. Control Structures

Like many other languages, PHP supports many different control structures that can be used to execute particular blocks of code based on decisions or repeat blocks of code while a particular condition is true. The following sections cover the various control structures available in PHP.

30.2.1. Do-while

The do-while loop executes one or more lines of code as long as a specified condition remains true. This structure has the following format:

do {
  // statement(s) to execute
} while (<expression>);

Due to the expression being evaluated at the end of the structure, statement(s) in a do-while loop are executed at least once. The following example will loop a total of 20 times—incrementing the variable $x each time until $x reaches the value 20:

$x = 0;
do {
  $x++;  // increment x
} while ($x < 20);

30.2.2. While

The while loop executes one or more lines of code while a specified expression remains true. The while loop has the following syntax:

while (<expression>) {
  // statement(s) to execute

Because the <expression> is evaluated at the beginning of the loop, the statement(s) will not be executed if the <expression> is false at the beginning of the loop. For example, the following loop will execute 20 times, each iteration of the loop incrementing $x until it reaches 20:

$x = 1;
while ($x <= 20) {  // do until $x = 20 (will not execute when x = 21)
  $x++;  // increment $x

30.2.3. For

The for loop executes statement(s) a specific number of times, governed ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.