18

I've seen this code, and I've no idea what it means.

while(true){
    echo "Hello world";
}

I know what a while loop is, but what does while(true) mean? How many times will it executed. Is this not an infinite loop?

0

5 Answers 5

27

Although is an infinite loop you can exit it using break. It is useful when waiting for something to happen but you don't exactly know the number of iteration that will get you there.

13

Yes, this is an infinite loop.

The explicit version would be

while (true == true)
20
  • 2
    @Ignacio you mean signed vs. unsigned true. Those are coming in PHP 7, I'm told
    – Pekka
    Nov 25, 2010 at 12:12
  • 9
    Not explicit enough. while (((((true == true) == true) == true) == true) == true){ Nov 25, 2010 at 12:14
  • 2
    and the inverse: while (true != false) and back: while ((true != false )==true)
    – bcosca
    Nov 25, 2010 at 12:21
  • 5
    I do not see why (true == true) should be more explicit than (true) Dec 24, 2015 at 10:55
  • 2
    @Pekka, given that at the end the result is a boolean expression, it seems to me that the expression "true" (the most readable boolean expression possible) is better than "true == true". Using the same approach, If you need the expression false what would you write ? false == true ? Dec 24, 2015 at 11:02
5

This is indeed (as stated already) an infinite loop and usually contains code which ends itself by using a 'break' / 'exit' statement.

Lots of daemons use this way of having a PHP process continue working until some external situation has changed. (i.e. killing it by removing a .pid file / sending a HUP etc etc)

5

Please referes to the PHP documentation currently at: http://www.w3schools.com/php/php_looping.asp

The while loop executes a block of code as long as the specified condition is true.

while (expression) {
    statement(s) 
} 

The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.

As a consequence, the code:

while (true) {
    statement(s)
}

will execute the statements indefinitely because "true" is a boolean expression that, as you can expect, is always true.

As already mentioned by @elzo-valugi, this loop can be interrupted using a break (or exit):

while (true) {
    statement(s)
    if (condition) {
        break;
    }
}
1
3

It is indeed an infinite loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.