The while loop sets off a section of code to repeat with braces. It uses the keyword WHILE followed by a condition when the looping should stop. Here's a basic example:
<?php $remaining_donuts = 12; while ($remaining_donuts > 0) { echo "I'm eating a donut...<br />"; $remaining_donuts--; } echo "I ate them all!"; ?>
We first assign the value of 12 to the variable $remaining_donuts. Then, for each donut that's eaten, a message is outputted and the value of $remaining_donuts is decremented by one.
The section of code is not processed after the value of $remaining_donuts is no longer greater than 0. The normal flow of the script continues past the code block and a concluding "I ate them all!" message is outputted.
It's important to be careful when constructing a looping condition and when adjusting the variables' values in the code block. For example, code which adjusts the value of $remaining_donuts incorrectly would loop indefinitely!
<?php $remaining_donuts = 12; while ($remaining_donuts > 0) { echo "I'm eating a donut...<br />"; $remaining_donuts++; } echo "I ate them all!"; ?>
Note the while loop evaluates the condition before it executing the code block. If the statement resolves false then the loop's code is skipped and the flow of the script continues afterwards. If the value of $remaining_donuts was set to 0 or a negative number, for example, the braced code will not be executed and the script will simply display "I ate them all!"
<?php $remaining_donuts = 0; while ($remaining_donuts > 0) { echo "I'm eating a donut...<br />"; $remaining_donuts--; } echo "I ate them all!"; ?>
Conditional expressions is beyond the intended scope of this tutorial, so if you need assistance with comparison operators and how PHP makes decisions, I recommend my previous tutorial, A Tour of Decision Making Structures in PHP.