Page 100 - Beginning PHP 5.3
P. 100
Part II: Learning the Language
The loop sets up a new counter variable, $i , and sets its value to 1 . The code within the loop displays the
current counter value. Each time the loop repeats, $i is incremented. The loop test expression checks to
see if $i is still less than or equal to 10 ; if it is, the loop repeats. Once $i reaches 11, the loop exits and the
“ All done! ” message is displayed.
It ’ s perfectly possible to write any for loop using a while statement instead. Here ’ s the previous for
loop rewritten using while :
$i = 1;
while ( $i < = 10 ) {
echo “I ’ ve counted to: $i < br / > ”;
$i++;
}
echo “All done!”;
However, as this example clearly shows, a for loop is generally neater and more compact.
There ’ s a lot more to the for statement than meets the eye. For example, you don ’ t have to use it for
simple counting, nor does the loop test expression have to involve the same variable that ’ s in the
counting expression. Here ’ s an example:
$startTime = microtime( true );
for ( $num = 1; microtime( true ) < $startTime + 0.0001; $num = $num * 2 ) {
echo “Current number: $num < br / > ”;
}
echo “Out of time!”;
You ’ re probably wondering what on earth this script does. Well, it races the PHP engine against
the clock!
First, the script stores the current Unix timestamp, in microseconds, in a variable, $startTime . To do
this, it uses PHP ’ s microtime() function with an argument of true , which returns the current
timestamp as a floating - point number (with the number of seconds before the decimal point and the
fraction of a second after the decimal point).
Next, the for loop goes into action. The initializer sets up a variable, $num , with a value of 1 . The loop
test expression checks to see if the current time — again retrieved using microtime() — is still earlier
than 1/10000th of a second (100 microseconds) after the start time; if it is the loop continues. Then the
counting expression, rather than simply incrementing a counter, multiplies the $num variable by 2 .
Finally, the body of the loop simply displays the current value of $num .
So to summarize, the for loop sets $num to 1 , then keeps multiplying $num by 2 , displaying the result
each time, until 100 microseconds have elapsed. Finally, the script displays an “ Out of time! ” message.
To try out this race, save the code as race.php and open the script ’ s URL in your Web browser. Exactly
how far this script will get depends on the speed of your Web server! On my computer it made it up to 8
before running out of time, as shown in Figure 4 - 3 .
62
9/21/09 8:52:10 AM
c04.indd 62
c04.indd 62 9/21/09 8:52:10 AM