• Tutorial List

PHP While Loop

Last updated May 15, 2020
PHP While Loop

How does work the PHP While loop?

The PHP While Loop executes a block of code repeatedly until the specified condition is false.

How does work the PHP While loop?

Syntax of the While Loop

<?php
  while(condition){
     //block of code
  }
?>

PHP While Loop Example

The following example displays the numbers from 1 to 3.

<?php
  $i = 1;
  while($i < 4){
      echo $i ."<br>";
      $i++;
  }
?>
Browser Output
1
2
3

Explanation of the above example:

When the Loop Starts –

  1. ($i < 4) – First, it checks the condition. The condition is – the $i(1) is less than 4, and the condition is true so this loop will run.
  2. $i++ – It increases the $i value. ($i + 1 = 2)

Second time Loop:

  1. After increasing the $i, Now $i value is 2.
  2. ($i < 4) – It checks the condition again, and the condition is true so this loop will run again.
  3. And then, it increases the $i value again. ($i + 1 = 3)

Third-time Loop:

  1. In the third time, the $i value is 3, and It checks the condition again and the loop will run because, the condition ($i > 4) is true.
  2. Then It increases the $i value again. ($i + 1 = 4)

Fourth-time Loop:

In the fourth time, the $i value is 4, and It checks the condition again. But at the fourth time, this condition ($i > 4) is false so this loop will be closed.