How to create a while loop in PHP
How to create a while loop in PHP
In this post snipped I’ll show you an easy way to create simple while loops and multiple or nested while loops.
Scenario
Create a counting script that stops once it reaches 10 and it also prints the count to the user once the execution has finished.
Solution
1 2 3 4 5 6 7 8 |
<?php $count = 0; while ($count < 10){ echo "Count is: " . $count."<br/>"; $count++; } echo "Count has been completed"; ?> |
Output
1 2 3 4 5 6 7 8 9 10 11 |
Count is: 0 Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count has been completed |
Multiple while loops in PHP
Heads up! Don’t forget that nesting loops within another loop will have the main loop hang (wait) until the nested one is completed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $count = 0; $second = 0; while ($count < 4){ while ($second < 4){ echo "Second is: " . $second."<br/>"; $second++; } if ($second == 4) { $second = 0; } echo "Count is: " . $count."<br/>"; $count++; } echo "Count has been completed"; ?> |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Second is: 0 Second is: 1 Second is: 2 Second is: 3 Count is: 0 Second is: 0 Second is: 1 Second is: 2 Second is: 3 Count is: 1 Second is: 0 Second is: 1 Second is: 2 Second is: 3 Count is: 2 Second is: 0 Second is: 1 Second is: 2 Second is: 3 Count is: 3 Count has been completed |
That’s it with php while loops, from here you can take another step further and think it with arrays for example.