Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

Loops 665

24


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 = array('red', 'green', 'blue');
$looking_for = 'red';
foreach ($colors as $color) {
if ($color = $looking_for) {
echo "Found $color.\n";
break;
}
}


In this example, I’m searching for a particular color. When the foreach loop gets to the
array element that matches the color I’m looking for, I print the color out and use the
break statement to stop the loop. When I’ve found the element I’m looking for, there’s
no reason to continue.


I could accomplish the same thing a different way using continue, like this:


$colors = array('red', 'green', 'blue');
$looking_for = 'red';
foreach ($colors as $color) {
if ($color != $looking_for) {
continue;
}


echo "Found $color.\n";
}

Free download pdf