PHP while Loop
In the previous chapter we have seen the different looping statements such as for loop and for each loop to iterate array. In the chapter we will be learning the another way of looping statement in PHP.
PHP While loop :
- In order to execute some statements repetitively we use while loop based on the condition specified in the while.
- If condition fails then control goes outside the while loop. If condition becomes true then while loop body will be executed.
- True condition can be any non-zero number and Zero is considered as false condition
Syntax for the while-loop :
while(condition) { statement(s); }
Flowchart of the while loop :
Example #1 : While loop
<html> <body> <?php $i = 0; $num = 5; while( $i < $num) { echo "Value of i = $i" . "<br />"; $i++; } ?> </body> </html>
Output :
Value of i = 0 Value of i = 1 Value of i = 2 Value of i = 3 Value of i = 4
Example #2 : While loop (Alternate Syntax)
<html> <body> <?php $i = 1; while ($i <= 5): echo $i; $i++; endwhile; ?> </body> </html>
Output :
12345
Explanation :
In this example we have completly skipped the opening and closing curly braces. In this example we have just replaced opening curly with colon and closing curly with endwhile.
Text | Replaced by |
---|---|
{ | : |
} | endwhile; |