0

Does anyone know in which cases may infinite loop be useful in PHP?

Example :

<?php
  while(true)
  {
    #..
  }
?>
John
  • 7,500
  • 16
  • 62
  • 95
  • Might be help full for cronjobs. Or notifications scripts. – Muhammad Zeeshan Jun 07 '12 at 11:02
  • 1
    Oh. Once again it occurred. I typed in my response and found a duplicate - http://stackoverflow.com/questions/1765733/when-are-infinite-loops-are-useful-in-php and the very first answer echoes my opinions... :) – verisimilitude Jun 07 '12 at 11:33

7 Answers7

6

Few Use cases.

1) If you are writing a program to allow input data for as long as the user wants, 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.
2) If you have some background process monitoring your servers continuously.
3) Possibly a very good usage is when your server script is listening to a socket for connections.
4) Video Game programming use them heavily.

I differ from some of the above answers posted above which say that "infinite loops are useless".

http://devzone.zend.com/209/writing-socket-servers-in-php/ - An example of infinite loops been put to use.

verisimilitude
  • 5,077
  • 3
  • 30
  • 35
2

Hey these are very essential in case you want to create a service kind of a thing, may be you want to monitor the server space ,i mean you want to see if there any new files added etc. you can then use such a loop and monitor 24*7.

I use it quite often in c++,in php too it can be used.

samairtimer
  • 826
  • 2
  • 12
  • 28
1

This isn't really PHP specific. Infinite loops are useful when you don't know in advance amount of work you need to do.

  1. Jobs that indeed run forever until terminated.
  2. Jobs that wait for something to happen and break loop to continue with code after it.
Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
1
  1. Jobs that need a certain condition to be met before another action is performed.
  2. Jobs that should run till terminated by the user
Magondu
  • 197
  • 5
  • 20
1

It is almost useless. True is that it can be used with break as Oleg V. Volkov mentioned but You'll have to add condition into block but while is a loop with condition itself. From my point of view it is wrong usage.

Lweek
  • 156
  • 1
  • 7
1

Infinite loop allows you to iterate through unknown set of data, until terminated (brake). or you are performing some actions that need to run until interrupted by user or else. It all depends on what you need to do and how would you tackle the problem.

greenLizard
  • 2,326
  • 5
  • 24
  • 30
0

Two cases :

  • PHP is used on server-side : usually useless since it blocks loading of the page, which isn't what you want for the user.
  • PHP is used client side (local program) : useful for the reasons posted before (waiting for user demand to exit loop).
Jean-Marie Comets
  • 706
  • 2
  • 7
  • 21