Page 101 - Beginning PHP 5.3
P. 101
Chapter 4: Decisions and Loops
Figure 4-3
It ’ s worth pointing out that having a complex loop test expression can seriously slow down your script,
because the test expression is evaluated every single time the loop repeats. In the example just shown,
the expression needs to be fairly processor - intensive because it has to retrieve the current time — an
ever - changing value. However, generally it ’ s better to pre - compute as much of the test expression as you
can before you enter the loop. For example:
$secondsInDay = 60 * 60 * 24;
for ( $seconds = 0; $seconds < $secondsInDay; $seconds++ ) {
// Loop body here
}
is generally going to be a bit faster than:
for ( $seconds = 0; $seconds < 60 * 60 * 24; $seconds++ ) {
// Loop body here
}
You can actually leave out any of the expressions within a for statement, as long as you keep the
semicolons. Say you ’ ve already initialized a variable called $i elsewhere. Then you could miss out the
initializer from the for loop, as follows:
for ( ; $i < = 10; $i++ ) {
// Loop body here
}
You can even leave out all three expressions if you so desire, thereby creating an infinite loop:
for ( ; ; );
Of course, such a loop is pretty pointless unless you somehow exit the loop in another way! Fortunately,
you can use the break statement — discussed in the next section — to do just that.
63
9/21/09 8:52:11 AM
c04.indd 63
c04.indd 63 9/21/09 8:52:11 AM