..while are similar in function. The only real difference is that
the code embedded within a while statement possibly could never be executed,
whereas the code embedded within a do...while statement will always execute at
least once. Consider the following example:
$count = 11;
do {
printf("%d squared = %d
", $count, pow($count, 2));
} while ($count < 10);
?>
The following is the outcome:
11 squared = 121
104 CHAPTER 3 ?– PHP B ASICS
Despite the fact that 11 is out of bounds of the while conditional, the embedded code
will execute once because the conditional is not evaluated until the conclusion.
The for Statement
The for statement offers a somewhat more complex looping mechanism than does
while. The following is its syntax:
for (expression1; expression2; expression3) {
statements
}
There are a few rules to keep in mind when using PHP??™s for loops:
??? The first expression, expression1, is evaluated by default at the first iteration of
the loop.
??? The second expression, expression2, is evaluated at the beginning of each iteration.
This expression determines whether looping will continue.
??? The third expression, expression3, is evaluated at the conclusion of each loop.
??? Any of the expressions can be empty, their purpose substituted by logic
embedded within the for block.
With these rules in mind, consider the following examples, all of which display a
partial kilometer/mile equivalency chart:
// Example One
for ($kilometers = 1; $kilometers <= 5; $kilometers++) {
printf("%d kilometers = %f miles
", $kilometers, $kilometers*0.
Pages:
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189