PHP while Loop

The while loop in PHP, is used when we need to execute some block of code, multiple times. For example:

   $x = 1;
      echo $x, "<BR>";

The output produced by above PHP example, is:

php while loop

PHP while Loop Syntax

The syntax to use while loop in PHP, is:

   block of code;

The block of code; will continue its execution, until the condition evaluates to be false.

PHP while Loop Example

The following example on while loop in PHP, is created along with its output and in-depth description:

   $num = 2;
      echo $num, "<BR>";
      $num = $num+2;

The output of above PHP example, is shown in the snapshot given below:

php while loop example

Note - Whatever the expression inside the while() will be considered as a conditional expression. After evaluating a conditional expression, a boolean value (true or false) gets returned. If the boolean value is true, then execution of while loop continues, otherwise if the conditional expression evaluates to be false, then the execution of while loop stops.

The dry run of above example, goes like:

  1. A variable $num is defined with its value as 2
  2. Now the execution of while loop begins
  3. Since at first, the condition $num<=20 or 2<=20 evaluates to be true
  4. Therefore program flow goes inside the loop
  5. Using the statement:
    echo $num, "<BR>";
  6. The value of $num, that is 2, along with a line break, will be printed on the output
  7. Now the second statement of the loop, that is:
    $num = $num+2;
    gets executed
  8. Therefore $num+2 or 2+2 or 4 will be initialized to $num. Now $num = 4
  9. As all the statements inside the loop has been executed, therefore program flow again goes to the conditional expression of the while loop, to check the condition again
  10. Second time, the condition $num<=20 or 4<=20 evaluates to be true again
  11. Therefore program flow again goes inside the loop
  12. Now the similar process goes again, from step no.5 to step no.9, with of course the new value of $num
  13. This process continues, until the value of $num becomes greater than 20
  14. Because, when the value of $num becomes greater than 20, then the condition $num<=20 evaluates to be false, and the execution of while loop stops

Let me create another example on while loop in PHP:

   $num = 5;
   $i = 1;
   echo "<p>----Table of $num----</p>";
      echo "$num * $i = ", $num*$i, "<BR>";

Now the output should be:

while loop in php

Following is one last example of while loop in PHP:

   $sum = 0;
   $count = 0;
   $check = true;
      if($sum === 500)
         $check = false;
         $sum += 10;
   echo "<p>Value of \$sum = ", $sum, "</p>";
   echo "<p>Number of times, loop executed = ", $count, "</p>";

The output should be:

Value of $sum = 500

Number of times, loop executed = 50

PHP Online Test

« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook

Subscribe Us on YouTube