Loops
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, while the foreach is used exclusively with arrays and
is discussed in the next chapter.
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 with 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)
{
print $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 previous while example as follows:
$counter = 1;
do
{
print $counter . " ";
$counter++;
} while ($counter < 11);The contrast between while
and do...while can be seen in the
following example:
$counter = 100; do { print $counter . " "; $counter++; } while ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access