Infinite loops

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, you should steer clear of infinite loops as they can 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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Special loop keywords >>

Previous chapter: Loops

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.