Loops


PHP supports several types of loops, some of which are generally more commonly used than others. As you know from the JavaScript lesson, loops execute code repeatedly until a condition of some kind is satisfied. PHP supports several types of loops: do...while, while, for, and foreach. I'll discuss them in reverse order.

foreach Loops

The foreach loop was created for one purposeto enable you to process all of the elements in an array quickly and easily. The body of the loop is executed once for each item in an array, which is made available to the body of the loop as a variable specified in the loop statement. Here's how it works:

$colors = array('red', 'green', 'blue'); foreach ($colors as $color) {   echo $color . "\n"; }


This loop prints each of the elements in the $colors array with a linefeed after each color. The important part of the example is the foreach statement. It specifies that the array to iterate over is $colors, and that each element should be copied to the variable $color so that it can be accessed in the body of the loop.

The foreach loop can also process both the keys and values in an associative array if you use slightly different syntax. Here's an example:

$synonyms = array('large' => 'big',                   'loud' => 'noisy',                   'fast' => 'rapid'); foreach ($synonyms as $key => $value) {     echo "$key is a synonym for $value.\n"; }


As you can see, the foreach loop reuses the same syntax that's used to create associative arrays.

for Loops

Use for loops when you want to run a loop a specific number of times. The loop statement has three parts: a variable assignment for the loop's counter, an expression (containing the index variable) that specifies when the loop should stop running, and an expression that increments the loop counter. Here's a typical for loop:

for ($i = 1; $i <= 10; $i++) {   echo "Loop executed $i times.\n"; }


$i is the counter (or index variable) for the loop. The loop is executed until $i is larger than 10 (meaning that it will run 10 times). The last expression, $i++, adds one to $i every time the loop executes. The for loop can also be used to process an array instead of foreach if you prefer. You just have to reference the array in the loop statement, like this:

$colors = array('red', 'green', 'blue'); for ($i = 0; $i < count(array); $i++) {   echo "Currently processing " . $colors[$i] . ".\n"; }


There are a couple of differences between this loop and the previous one. In this case, I start the index variable at 0, and use < rather than <= as the termination condition for the loop. That's because count() returns the size of the $colors array, which is 3, and loop indexes start with 0 rather than 1. If I start at 0 and terminate the loop when $i is equal to the size of the $colors array, it runs three times, with $i being assigned the values 0, 1, and 2, corresponding to the indexes of the array being processed.

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 determine 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 condition 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 running 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 statement 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;   } }


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


In this case, if the color is not the one I'm looking for, the continue statement stops executing the body of the loop and goes back to the loop condition. If the color is the one I'm looking for, the continue statement is not executed and the echo function goes ahead and prints the color name I'm looking for.

The loops I'm using as examples don't have a whole lot of work to do. Adding in the break and continue statements doesn't make my programs much more efficient. Let's say, however, that each iteration of my loop searches a very large file or fetches some data from a remote server. If I can save some of that work using break and continue, it could make my script much faster.




Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day
Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day (5th Edition)
ISBN: 0672328860
EAN: 2147483647
Year: 2007
Pages: 305

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net