PHP DevCenter
oreilly.comSafari Books Online.Conferences.

advertisement


PHP Foundations

Advanced Control Structures

04/19/2001

This article will cover advanced control structures and techniques, including multi-conditional if statements and an introduction to the for statement.

The 'for' loop

In our previous articles, we discussed using a while loop as a means to repeat a block of code until the condition it provided is determined to be false. Although useful, while loops are used primarily when you donít initially know how many times you want to execute the code block. The for statement is another repetition statement designed to be used when executing a code block a specific number of times. The syntax for a for loop is:

For(initialization; condition; increment) {
// Code to loop
}

Unlike the while loop, a for loop contains three parts separated by semicolons. When a for statement executes, the initialization statement is automatically executed. Then, once the initialization statement has finished, the condition provided is evaluated. If this condition is true, the code block enclosed within the for statement is then executed. After the code within the loop has been executed, the increment statement is evaluated and the condition is then re-evaluated. Note that in a for loop, the initialization statement is only evaluated once -- before any code within the loop is evaluated -- but the increment portion is evaluated after each iteration of the loop. This looping process (evaluate condition, evaluate block, evaluate increment statement) is continued until the conditions provided are false and the loop ends (See Figure 1).

Diagram of 'for' loop processing
Figure 1. Processing of a "for" loop.

Now that we have an idea of how a for statement works, let's see it in action by looking at the earlier example we used to demonstrate the workings of a while loop where we wanted to display a count of all the numbers between 1 and 5:

<?php

for($L = 1; $L <= 5; $L++) {

echo $L."<br />";

}
?>

As expected, the output is identical to the while loop and displays the numbers 1 through 5. Again note that the increment statement ($L++) could be any valid math statement. For example, we could count backwards from 5 to 1 by using the following:

<?php

for($L = 5; $L >= 1; $L--) {

echo $L."<br />";

}
?>

Pages: 1, 2

Next Pagearrow




Valuable Online Certification Training

Online Certification for Your Career
Earn a Certificate for Professional Development from the University of Illinois Office of Continuing Education upon completion of each online certificate program.

PHP/SQL Programming Certificate — The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux mySQL platform.

Enroll today!


Sponsored by: