Page 104 - Open Soource Technologies 304.indd
P. 104
Unit 6: Building Blocks of PHP
Sometimes, you want to terminate the execution of a loop in the middle of an iteration. For this Notes
purpose, PHP provides the break statement. If break appears alone, as in break; the innermost loop
is stopped. break accepts an optional argument of the amount of nesting levels to break out of,
break n;
which will break from the n innermost loops (break 1; is identical to break;). n can be any valid
expression. In other cases, you may want to stop the execution of a specific loop iteration and
begin executing the next one. Complimentary to break, continue provides this functionality.
continue alone stops the execution of the innermost loop iteration and continues executing
the next iteration of that loop. Continue n can be used to stop execution of the n innermost
loop iterations. PHP goes on executing the next iteration of the outermost loop. As the switch
statement also supports break, it is counted as a loop when you want to break out of a series
of loops with break n.
6.1.7.2 do...while Loops
do
statement
while (expr);
The do...while loop is similar to the previous while loop, except that the truth expression is
checked at the end of each iteration instead of at the beginning. This means that the loop always
runs at least once. do...while loops are often used as an elegant solution for easily breaking out
of a code block if a certain condition is met. Consider the following example:
do {
statement list
if ($error) {
break;
}
} while (false);
Because do...while loops always iterate at least one time, the statements inside the loop are
executed once, and only once. The truth expression is always false. However, inside the loop
body, you can use the break statement to stop the execution of the statements at any point, which
is convenient. Of course, do...while loops are also often used for regular iterating purposes.
6.1.7.3 For Loops
Statement Statement List
for (expr; expr; expr) statement for (expr, expr, …; expr, expr, …;
expr, expr, …):
statement list
endfor;
LOVELY PROFESSIONAL UNIVERSITY 99