2.6.11 Infinite loopsThis is NOT the latest copy of this book; click here for the latest version.
Perhaps surprisingly, infinite loops can sometimes be helpful in your scripts. As infinite loops never terminate without outside influence, the most popular way to use them is to break out of the loop and/or exit the script entirely from within the loop whenever a condition is matched. You can also rely on user input to terminate the loop - for example, if you are writing a program to accept people typing in data for as long as they want, it just would not work to have the script loop 30,000 times or even 300,000,000 times. Instead, the code should loop forever, constantly accepting user input until the user ends the program by pressing Ctrl-C.
While you are learning PHP, it is almost certainly best you steer clear of infinite loops, as they can really cause problems in the first few weeks. After that, try playing around with them to see how they can actually help you make your scripts better. Having said that, you will almost certainly make a few loops carry on forever simply by accident!
If you want to try them out, here are the most common examples of infinite loops:
<?php
while(1) {
print "In loop!\n";
} ?>
As "1" also evaluates to true, that loop will continue on forever. Many people also like to write their infinite loops like this:
<?php
for (;;) {
print "In loop!\n";
} ?>
In that example, the for loop is missing the declaration, condition, and action parts, meaning that it will always loop.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|