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?
while True means loop forever. The while statement takes an expression and executes the loop body while the expression evaluates to (boolean) "true". True always evaluates to boolean "true" and thus executes the loop body indefinitely. It's an idiom that you'll just get used to eventually!
The while loop executes a block of code as long as the specified condition is true.
while True: ... means infinite loop. The while statement is often used of a finite loop.
You can stop an infinite loop with CTRL + C . You can generate an infinite loop intentionally with while True . The break statement can be used to stop a while loop immediately.
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.
Yes, this is an infinite loop.
The explicit version would be
while (true == true)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With