Loops

Loops in PHP have the same syntax as other high-level programming languages.

Loops add control to scripts so that statements can be repeatedly executed as long as a conditional expression remains true. There are four loop statements in PHP: while, do...while, for, and foreach. The first three are general-purpose loop constructs, and foreach is used exclusively with arrays.

while

The while loop is the simplest looping structure but sometimes the least compact to use. The while loop repeats one or more statements—the loop body—as long as a condition remains true. The condition is checked first, then the loop body is executed. So, the loop never executes if the condition isn’t initially true. Just as in the if statement, more than one statement can be placed in braces to form the loop body.

The following fragment illustrates the while statement by printing out the integers from 1 to 10 separated by a space character:

$counter = 1;
while ($counter < 11)
{
  echo $counter;
  echo " ";
  // Add one to $counter
  $counter++;
}

do...while

The difference between while and do...while is the point at which the condition is checked. In do...while, the condition is checked after the loop body is executed. As long as the condition remains true, the loop body is repeated.

You can emulate the functionality of the while example as follows:

$counter = 1;
do
{
  echo $counter;
  echo " ";
  $counter++;
} while ($counter < 11);

The contrast between while and do...while can be seen in the following example: ...

Get Web Database Applications with PHP, and MySQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.