Open In App

PHP while Loop

Improve
Improve
Like Article
Like
Save
Share
Report

The while loop is the simple loop that executes nested statements repeatedly while the expression value is true. The expression is checked every time at the beginning of the loop, and if the expression evaluates to true then the loop is executed otherwise loop is terminated.

Flowchart of While Loop:

 

Syntax:

while (if the condition is true) {
    // Code is executed
}

Example 1: This example uses a while loop to display numbers.

PHP




<?php
  
      // Declare a number
      $num = 10;
  
      // While Loop
      while ($num < 20) {
          echo $num . "\n";
          $num += 2;
      }
?>


Output

10
12
14
16
18

while-endWhile loop:

Syntax:

while (if the condition is true):
    // Code is executed
    ...
endwhile;

Example 2: This example uses while and endwhile to display the numbers.

PHP




<?php
  
    // Declare a number
    $num = 10;
  
    // While Loop
    while ($num < 20):
        echo $num . "\n";
        $num += 2;
    endwhile;
?>


Output

10
12
14
16
18

Reference: https://www.php.net/manual/en/control-structures.while.php



Last Updated : 22 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads