Helping ordinary people create extraordinary websites!

Basic Control Structures in PHP

By Darren W. Hedlund
2005-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
}

Diagram of while loop.
Figure 1. Processing of a while loop.

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:
 1 Votes

You might also want to check these out:


Leave a Comment on "Basic Control Structures in PHP"
You must be logged in to post a comment.

Link to This Tutorial Page!


GET OUR NEWSLETTERS