When are infinite loops are useful in PHP?

taabouzeid picture taabouzeid · Nov 19, 2009 · Viewed 16.1k times · Source

While reading through the great online PHP tutorials of Paul Hudson he said

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.

Would you please give me a simple running example of how to use infinite loops in PHP ?

Answer

Ben S picture Ben S · Nov 19, 2009

Monitoring applications

If you have a background process that monitors the state of your servers and sends an email if trouble occurs. It would have an infinite loop to repeatably check the servers (with some pause between iterations.)

Server listening for Clients

If you have a server script that listens to a socket for connections, it will loop infinitely, blocking while waiting for new clients to connect.

Video Games

Games usually have a "game loop" that runs once a frame, indefinitely.

Or... anything else that needs to keep running in the background with periodic checks.