Specifications

The basic structure of a for loop is
for( expression1; condition; expression2)
expression3;
expression1 is executed once at the start. Here you will usually set the initial value of a
counter.
The condition expression is tested before each iteration. If the expression returns false,
iteration stops. Here you will usually test the counter against a limit.
expression2 is executed at the end of each iteration. Here you will usually adjust the
value of the counter.
expression3 is executed once per iteration. This expression is usually a block of code and
will contain the bulk of the loop code.
We can rewrite the
while loop example in Listing 1.4 as a for loop. The PHP code will
become
<?
for($distance = 50; $distance <= 250; $distance += 50)
{
echo “<tr>\n <td align = right>$distance</td>\n”;
echo “ <td align = right>”. $distance / 10 .”</td>\n</tr>\n”;
}
?>
Both the while version and the for version are functionally identical. The for loop is some-
what more compact, saving two lines.
Both these loop types are equivalentneither is better or worse than the other. In a given situa-
tion, you can use whichever you find more intuitive.
As a side note, you can combine variable variables with a for loop to iterate through a series
of repetitive form fields. If, for example, you have form fields with names such as name1,
name2, name3, and so on, you can process them like this:
for ($i=1; $i <= $numnames; $i++)
{
$temp= “name$i”;
echo $$temp.”<br>”; // or whatever processing you want to do
}
By dynamically creating the names of the variables, we can access each of the fields in turn.
Using PHP
P
ART I
46
03 7842 CH01 3/6/01 3:39 PM Page 46