Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

The problem is that it is very easy to forget to put the increment in. The result is an
infinite loop. The for loop puts all this functionality in one place. Inside the for
statement you give it three things: an initialization statement, a boolean expression, and
an increment statement. Figure 3-5 defines a for loop.


Figure 3-5. The for statement.

When first encountered, the initialization statement is executed. This traditionally takes
the form of assigning a variable to be 0 or 1. Then, as with a while statement, the
boolean expression is evaluated. If FALSE, control jumps to just after the code block.
Otherwise, the code block is executed. Before the boolean expression is evaluated again,
the increment statement is executed. This puts all the information needed for running the
loop in one place and forces you to think about all the steps. Listing 3.9 is a very simple
for loop but is typical in form.


Listing 3.9 A Typical for Loop

Free download pdf