The while loop runs a block of code as long as the specified condition is true.
Display $i as long as $i is less than 6:
$i = 1; |
Note: Don’t forget to increment $i, or the loop will run indefinitely. |
The while loop doesn’t run a set number of times but checks after each iteration if the condition is still true.
The condition doesn’t need to be a counter; it could be the status of an operation or any condition that evaluates to true or false.
We can use the break statement to stop the loop, even if the condition remains true:
Terminate the loop when $i is 3:
$i |
The continue statement allows us to skip the current iteration and move on to the next one:
Skip to the next iteration if $i is 3:
$i |
The while loop syntax can also be expressed using the endwhile statement, as follows:
Output $i as long as $i is less than 6:
$i |
If you want the while loop to count to 100 in increments of 10, you can increase the counter by 10 instead of 1 in each iteration:
Count to 100 in increments of ten:
$i |