Section 4.13. Special Loop Keywords


4.13. Special Loop Keywords

PHP gives you the break and continue keywords to control loop operation. We already used break previously when we looked at case switchingit was used there to exit a switch/case block, and it has the same effect with loops. When used inside loops to manipulate the loop behavior, break causes PHP to exit the loop and carry on immediately after it, and continue causes PHP to skip the rest of the current loop iteration and go on to the next.

Perl users should note that break and continue are equivalent to Perl's last and next statements.


For example:

     <?php             for ($i = 1; $i < 10; $i = $i + 1) {                     if ($i =  = 3) continue;                     if ($i =  = 7) break;                     print "Number $i\n";             }     ?>

That is a modified version of our original for loop script. This time, the output looks like this:

     Number 1     Number 2     Number 4     Number 5     Number 6

Note that Number 3 is missing, and the script exits after Number 6. When the current number is 3, continue is used to skip the rest of that iteration and go on to Number 4. Also, if the number is 7, break is used to exit the loop altogether.



PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net