Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does while (true){ mean in PHP?

Tags:

php

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?

like image 897
stevenmc Avatar asked Nov 25 '10 12:11

stevenmc


People also ask

What is the meaning of while true?

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!

What is a while loop in PHP?

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

What is a while true loop called?

while True: ... means infinite loop. The while statement is often used of a finite loop.

How do you break from while true?

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.


3 Answers

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.

like image 82
Elzo Valugi Avatar answered Oct 24 '22 23:10

Elzo Valugi


Yes, this is an infinite loop.

The explicit version would be

while (true == true)
like image 22
Pekka Avatar answered Oct 24 '22 22:10

Pekka


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)

like image 26
Gekkie Avatar answered Oct 24 '22 22:10

Gekkie