PHP While Loop

PHP While Loop Control Statement executes block of code as long as given condition is true. While Loop will first check condition before entering in loop body. If while condition is true, then the block of code will be executed.
Syntax:
//initialization here
while (condition is true) {
  //block of code to be executed;
 // Increment/Decrement iteration here
}

Example :

The below example displays the numbers from 1 to 8.
<?php
$num = 1;
while($num <= 8) {
  echo "The number is: $num <br>";
  $num++;
}
?>
Explain :
    $num = 1; - Initialize the loop counter ($num), and set the start value to 1
    $num <= 8 - Continue the loop as long as $num is less than or equal to 8
    $num++; - Increase the loop counter value by 1 for each iteration


Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8

PHP Nested While Loop : 
We can use php while loop inside another while loop in PHP, it is called as nested while loop.

Syntax:
//Main while loop initialization here
while (condition is true) {

          //initialization for nested while loop here
          while (condition is true) {
             //nested while loop body block of code to be executed;
            // nested while loop Increment/Decrement iteration here
          }
  //Main while loop block of code to be executed;
 // Main while loop Increment/Decrement iteration here
}

PHP Example :

<?php    
    $i=1;    
    while($i<=2){    // Main while loop
    $j=1;    
        while($j<=5){    // nested while loop
            echo "I:$i | J:$j<br/>";    
            $j++;    
        }
    echo "-----------<br/>";        
    $i++;    
    }    
 ?> 

PHP Output :

I:1 | J:1
I:1 | J:2
I:1 | J:3
I:1 | J:4
I:1 | J:5
-----------
I:2 | J:1
I:2 | J:2
I:2 | J:3
I:2 | J:4
I:2 | J:5
-----------

 

Comments

Leave a Reply

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

83298