While reading through the great online PHP tutorials of Paul Hudson he said
Perhaps surprisingly, infinite loops can sometimes be h
I'm going to disagree with the other answers so far, and suggest that, if you're being careful about things, they never have a place.
There is always some condition in which you want to shut down, so at the very least, it should be while(test if shutdown not requested) or while(still able to meaningfully run)
I think practically there are times when people don't use the condition and rely on things like sigint to php to terminate, but this is not best practice in my opinion, even if it works.
The risk of putting the test inside the loop and breaking if it fails is that it makes it easier for the code to be modified in the future to inadvertently create an endless loop. For example, you might wrap the contents of the while loop inside another loop, and then all of a sudden the break statement doesn't get you out of the while...
for(;;) or while(1) should be avoided whenever possible, and it's almost always possible.
There are many ways to use infinite loops, here is an example of an infinite loop to get 100 random numbers between 1 and 200
$numbers = array();
$amount = 100;
while(1) {
$number = rand(1, 200);
if ( !in_array($number, $numbers) ) {
$numbers[] = $number;
if ( count($numbers) == $amount ) {
break;
}
}
}
print_r($numbers);
Infinite loops are particulary useful when creating command line applications. The application will then run until the user tells it to stop. (add a break/exit-statement when the user input is "quit", for instance)
while (true) {
$input = read_input_from_stdin();
do_something_with_input();
if ($input == 'quit') {
exit(0);
}
}
Sometimes instead of a loop which would have an exit condition too long to preserve readability an improperly named "infinite" loop may be the best way to go.
<?php
while(1) {
// ...
$ok=preg_match_all('/.../',$M,PREG_SET_ORDER);
if (!$ok) break;
switch(...) { ... }
// match another pattern
$ok=preg_match('/.../',$M,PREG_SET_ORDER);
if (!$ok) break;
//and on, and on...
}
Paul Biggar has posted a make script for LaTeX projects which uses an infinite loop to run in the background and continually tries to rebuild the LaTeX sources.
The only way to terminate the script is to kill it externally (e.g. using Ctrl+C).
(Granted, not PHP (Bash, actually) but the same script could well be implemented in PHP instead.)
For user input...
while True:
input = get_input_from_user("Do you want to continue? ")
if input not in ("yes", "y", "no", "n"):
print "invalid input!"
else:
break