Loops and PHP Decision Making - for Loops
(Page 4 of 5 )
for loops provide the same general functionality as while loops, but also provide for a predefined location for initializing and changing a counter value. Their syntax is:
for (initialization expression; condition expression; modification expression){
code that is executed;
}
Figure 4-4 shows a flowchart for a for loop.

Figure 4-4. How a for loop executes
An example for loop is:
<?php
for ($num = 1; $num <= 10; $num++) {
print "Number is $num<br />\n";
}
?>
This produces the following:
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
| Number is 6
Number is 7
Number is 8
Number is 9
Number is 10
When your PHP program process the for loop, the initialization portion is evaluated. For each iteration of the portion of code that increments, the counter executes and is followed by a check to see whether you're done. The result is a much more compact and easy-to-read statement.
When specifying your for loop, if you don't want to include one of the expressions, such as the initialization expression, you may omit it, but you must still include the separating semicolons (;). Example 4-16 shows the usage of a for loop without the initialization expression.
Next: Breaking Out of a Loop >>
More Programming Basics Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the book Learning PHP and MySQL, Second Edition, written by Michele Davis and Jon Phillips (O'Reilly, 2006; ISBN: 0596101104). Check it out today at your favorite bookstore. Buy this book now.
|
|