Page 103 - Beginning PHP 5.3
P. 103
Chapter 4: Decisions and Loops
for ( $i=1; $i < = 10; $i++ ) {
if ( $i == 4 ) continue;
echo “I ’ ve counted to: $i < br / > ”;
}
echo “All done!”;
Though break and continue are useful beasts when you need them, it ’ s best not to use them unless
you have to. They can make looping code quite hard to read if they ’ re overused.
Creating Nested Loops
There ’ s nothing to stop you creating a loop inside another loop. In fact, this can be quite a useful
technique. When you nest one loop inside another, the inner loop runs through all its iterations first.
Then the outer loop iterates, causing the inner loop to run through all its iterations again, and so on.
Here ’ s a simple example of nested looping:
for ( $tens = 0; $tens < 10; $tens++ ) {
for ( $units = 0; $units < 10; $units++ ) {
echo $tens . $units . “ < br / > ”;
}
}
This example displays all the integers from 0 to 99 (with a leading zero for the numbers 0 through 9).
To do this, it sets up two loops: an outer “ tens ” loop and an inner “ units ” loop. Each loop counts from 0
to 9. For every iteration of the “ tens ” loop, the “ units ” loop iterates 10 times. With each iteration of the
“ units ” loop, the current number is displayed by concatenating the $units value onto the $tens value.
Note that the outer loop iterates 10 times, whereas the inner loop ends up iterating 100 times: 10
iterations for each iteration of the outer loop.
Nested loops are great for working with multidimensional data structures such as nested arrays and
objects. You ’ re not limited to two levels of nesting either; you can create loops inside loops inside loops,
and so on.
When using the break statement with nested loops, you can pass an optional numeric argument to indicate
how many levels of nesting to break out of. For example:
// Break out of the inner loop when $units == 5
for ( $tens = 0; $tens < 10; $tens++ ) {
for ( $units = 0; $units < 10; $units++ ) {
if ( $units == 5 ) break 1;
echo $tens . $units . “ < br / > ”;
}
}
// Break out of the outer loop when $units == 5
for ( $tens = 0; $tens < 10; $tens++ ) {
for ( $units = 0; $units < 10; $units++ ) {
if ( $units == 5 ) break 2;
echo $tens . $units . “ < br / > ”;
}
}
65
9/21/09 8:52:11 AM
c04.indd 65
c04.indd 65 9/21/09 8:52:11 AM