PHP While Loop Tutorial

Here you will learn about PHP While Loop. But before going further, you should learn first –


हिंदी | PHP While Loop in Hindi


Syntax of the While Loop

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

How does work the PHP While loop?

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

PHP While Loop

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:

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.


Quick Notes:

What is the PHP While loop?

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

Leave a Reply

Your email address will not be published. Required fields are marked *