HTML and CSS Reference
In-Depth Information
while
and
do...while
Loops
Both
for
and
foreach
are generally used when you want a loop to iterate a specific
number of times. The
while
and
do...while
loops, on the other hand, are designed to be
run an arbitrary number of times. Both loop statements use a single condition to deter-
mine whether the loop should continue running. Here's an example with
while
:
$number = 1;
while ($number != 5) {
$number = rand(1, 10);
echo “Your number is $number.\n”;
}
This loop runs until
$number
is equal to 5. Every time the loop runs,
$number
is assigned
a random value between 1 and 10. When the random number generator returns a 5, the
while
loop will stop running. A
do...while
loop is basically the same, except the condi-
tion appears at the bottom of the loop. Here's what it looks like:
$number = 1;
do {
echo “Your number is $number.\n”;
$number = rand(1, 10);
} while ($number != 5);
Generally speaking, the only time it makes sense to use
do
…
while
is when you want to
be sure the body of the loop will execute at least once.
Controlling Loop Execution
Sometimes you want to alter the execution of a loop. Sometimes you need to stop run-
ning the loop immediately, and other times you might want to just skip ahead to the next
iteration of the loop. Fortunately, PHP offers statements that do both. The
break
state-
ment is used to immediately stop executing a loop and move on to the code that follows
it. The
continue
statement stops the current iteration of the loop and goes straight to the
loop condition.
Here's an example of how
break
is used:
$colors = ('red', 'green', 'blue');
$looking_for = 'red';
foreach ($colors as $color) {
if ($color = $looking_for) {
echo “Found $color.\n”;
break;
}
}