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.
//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.
$num = 1;
while($num <= 8) {
  echo "The number is: $num <br>";
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

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.

//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 :

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

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



Leave a Reply

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