Microsoft Word - Sam's Teach Yourself MySQL in 21 Days - SAMS.doc

(singke) #1

Control Structures: for


A more complex form of looping is available in the form of the for loop. This takes the following form:


for (expression1; expression2; expression3) {
# some loop statements
}

The choice of expressions is important; these work as follows:
ƒ expression1 is evaluated only once, unconditionally, because execution starts at
for the first time.
ƒ expression2 is evaluated each time execution starts at for. If TRUE, the loop
statements are executed; if FALSE, you exit the loop.
ƒ expression3 is evaluated each time execution finishes the statements in the loop.
If TRUE, you execute the loop statements again; if FALSE, you exit the loop.
For example, consider how you could rewrite your countdown loop with for:
Countdown with for<br>
<?php
for ($n=4; --$n; $n)
echo "$n...";
?>
It really does just about the same as before. You start the loop by setting $n to 4; the second
expression decrements $n by 1 to 3, which evaluates to TRUE, so execution of the loop statements
begins.

(As before, when there's only one loop statement, you can omit the braces.)
At the end of the loop, you use the third expression to simply test if $n is still TRUE (non-zero). On the
fourth time through, the for will be zero (FALSE), at which point you finish looping.
Incidentally, you could equally have written the for loop as
for ($n=3; $n; $n--)
This sets $n to 3 the first time, and then checks that it's non-zero each time into the loop. At the end of
the loop each time, it decrements it. When it tries to start the loop the fourth time, $n will have been set
to zero, and it exits because the second expression is then FALSE.

Optional Commands for Loops: break and continue


You can use break anywhere within a for or while loop to break out of it immediately:


do {
# repeatable statements
if (expression) {
# some exceptional statements
break;
}
} while (expression)
# continue executing here
break is a way of leaving a loop "inelegantly." It lets you exit at any point during the loop and makes
execution skip to the code beyond the end of the loop.
The continue command is similar but less drastic; continue will force execution of the loop
statements to be curtailed, but not the loop itself. Execution skips to the end of the loop but not
necessarily out of it. It will try to keep executing the loop as normal, providing conditions are met.
Free download pdf