PHP while loop execute a multiple statements repeatedly until while expression is true.
Syntax of while loop:
Following is given a general syntax of while loop in PHP:
1 2 3 4 5 6 |
while(condition) { // statement; } |
The multiple statements inside while loop get executed only when expression is true.
These multiple statements enclosed within the curly braces or using the alternate syntax:
Initially if while condition is true then only while statements will execute otherwise they will not execute at even once.
1 2 3 4 |
while(condition): statement ... endwhile; |
Flowchart of PHP while loop
Example
1 2 3 4 5 6 7 8 |
<?php $a = 0; while($a <= 5) { echo "a = $a<br>"; $a++; } ?> |
Output:
1 2 3 4 5 6 |
a = 0 a = 1 a = 2 a = 3 a = 4 a = 5 |
Or you can use while loop as following:
It will print same output as above example only we use endwhile instead curly braces { }.
1 2 3 4 5 6 7 |
<?php $a = 0; while($a <= 5): echo "a = $a<br>"; $a++; endwhile; ?> |