login

While Loop Statement

PHP While loop is a simplest form of loop statement. Here are the forms of PHP while statement.

<?php
   while(condition){
      // code block to be executed
   }
   
   while(condition):
      // code block to be executed
   endwhile
?>

First while statement checks the condition. If the condition is true, the code block will be executed again and again as long as the condition is still true. The condition is checked again at the beginning of each iteration. So in the while statement, if the condition is false, it does not execute the code block inside the while statement. Here is an example of using while statement.

<?php

   $counter = 1;
   while($counter <= 10){
      // code block to be executed
      print("The current value of the counter is {$counter}<br/>");
      $counter++;
   }
   
?>

First we have a counter variable with value is 1. Then in the loop we output of the current value of the counter and increase it 1. Then the while statement check the value counter variable again and execute the code until the value of counter variable reach 10.

In some cases you want to escape the loop immediately at the middle of code block in the while statement. You can use break statement to do so. Here is an example of using break statement inside a while statement.

<?php

   $counter = 1;
   while(true){
      echo $counter;     // print counter
      if($counter == 5)  // if counter is 5 exit the loop,
        break;
      $counter++;        // increase 1
   }
?>

It is noted that while statement can be nested in other while statement.