Basic Control Structures in PHP
By Darren W. Hedlund2005-06-20
The while statement
The while statement is the most fundamental looping mechanism available to a PHP programmer. Although fundamentally different, it holds many similarities in syntax to an if statement, with the only real difference being that a segment of code within a while block will be executed as long as the condition in the while block is met (see figure 1). The syntax for a while loop is as follows:
While(conditions) {
// This code will execute until the conditions
// provided no longer evaluates to true
}
|
Looking at our earlier counting example, a much easier and more effective way to produce the same results using a while loop would be:
<?php $count = 1; while($count <= 5) { echo $count."<br />"; $count++; } ?>
As expected, the output for both examples is identical. Notice that by simply changing a few small aspects of this example, you can change the behavior of the while loop completely. (For example, instead of $count++ you could use $count += 2 and display only odd numbers.)
Tutorial Pages:
» Conditional blocks
» The if statement
» Basic looping
» The while statement
» Infinite loops
» Notes on embedding code blocks

