25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>PHP</strong> Basics ” 31<br />

Breaking and Continuing<br />

The break keyword, which we encountered briefly in the earlier section about the<br />

switch statement, can also be used to immediately exit a loop; it takes an optional<br />

parameter, which allows you to exit from multiple nested loops:<br />

i<br />

$i = 0;<br />

while (true) {<br />

if ($i == 10) {<br />

break;<br />

}<br />

echo $i . <strong>PHP</strong>_EOL;<br />

$i++;<br />

}<br />

for ($i = 0; $i < 10; $i++) {<br />

for ($j = 0; $j < 3; $j++) {<br />

if (($j + $i) % 5 == 0) {<br />

break 2; // Exit from this loop and the next one.<br />

}<br />

}<br />

}<br />

Remember to always terminate a break statement with a semicolon if it does not have<br />

any parameters. If you do not do so and it is followed by an expression that returns an<br />

integer number, you may end up causing the interpreter to randomly exit from more<br />

than one loop—causing all sorts of difficult-to-troubleshoot situations.<br />

There are cases in which, rather than terminating a loop, you simply want to skip<br />

over the remainder of an iteration and immediately skip over to the next. This is<br />

done with the continue statement—like with break, you can provide it an integer<br />

parameter to specify the level of nesting to which the it applies. For example, the<br />

following code will only output numbers between 0 and 3, and between 6 and 9:<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

for ($i = 0; $i < 10; $i++) {<br />

if ($i > 3 && $i < 6) {<br />

continue;<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!