Control Structures


while

while loops are the simplest type of loop. This executes the nested statements repeatedly, as long as the while expression evaluates to TRUE.

<?php
    $var = 0;
    while($var < 3)     // expression will be TRUE till third comparison
    {
      echo "$var\r\n";  // statement will be executed three times
      $var++;           // increase $var by one
      sleep(1);         // 1 second delay
    }
?>
[result]  
0
1
2
  • Infinite Loop
    You have to keep it in mind that repetitive statement can be repeated infinitely as if the result of expression is always TRUE. In this case, statement in the structure will be infinitely executed. This situation is called infinite loop.
<?php
    $var = 0;
    while(1)            // expression will always be TRUE
    {
      echo "$var\r\n";
      $var++;           // increase $var by one, $var = 1, 2, 3, …
      sleep(1);         // 1 second delay
    }
?>