Tuesday, March 2, 2021

PHP Tutorial Part 18 : PHP While Loop

PHP While Loop

PHP while loop can be used to traverse set of code like for loop. The while loop executes a block of code repeatedly until the condition is FALSE. Once the condition gets FALSE, it exits from the body of loop.

It should be used if the number of iterations is not known.

The while loop is also called an Entry control loop because the condition is checked before entering the loop body. This means that first the condition is checked. If the condition is true, the block of code will be executed.

Syntax

while(condition){  
//code to be executed  
}  

Alternative Syntax

while(condition):  
//code to be executed  
  
endwhile;  

PHP While Loop Example

<?php    
$n=1;    
while($n<=10){    
echo "$n<br/>";    
$n++;    
}    
?>  

Output:

1
2
3
4
5
6
7
8
9
10

Alternative Example

<?php    
$n=1;    
while($n<=10):    
echo "$n<br/>";    
$n++;    
endwhile;    
?>    

Output:

1
2
3
4
5
6
7
8
9
10

Example

Below is the example of printing alphabets using while loop.

<?php  
    $i = 'A';  
    while ($i < 'H') {  
        echo $i;  
        $i++;  
        echo "</br>";  
    }  
?>  

Output:

A
B
C
D
E
F
G

PHP Nested While Loop

We can use while loop inside another while loop in PHP, it is known as nested while loop.

In case of inner or nested while loop, nested while loop is executed fully for one outer while loop. If outer while loop is to be executed for 3 times and nested while loop for 3 times, nested while loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).

Example

<?php    
$i=1;    
while($i<=3){    
$j=1;    
while($j<=3){    
echo "$i   $j<br/>";    
$j++;    
}    
$i++;    
}    
?>    

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

PHP Infinite While Loop

If we pass TRUE in while loop, it will be an infinite loop.

Syntax

while(true) {    
//code to be executed    
}    

Example

<?php  
    while (true) {  
        echo "Hello onlinequizstock!";  
        echo "</br>";  
    }  
?>  

Output:

Hello onlinequizstock!
Hello onlinequizstock!
Hello onlinequizstock!
Hello onlinequizstock!
.
.
.
.
.
Hello onlinequizstock!
Hello onlinequizstock!

Previous Post
Next Post

post written by:

0 Comments: