Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

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:
» Conditional blocks
» The if statement
» Basic looping
» The while statement
» Infinite loops
» Notes on embedding code blocks


 | Bookmark
Related Tutorials:
» Zend Framework Tutorial
» Port Scanning and Service Status Checking in PHP
» Web Database Access from Desktop Applications
» CubeCart 3.0 Installation and Configuration
» PHP Site Search Made Easy
» Installing and Configuring Drupal 6.1