Breaking Out of Loops


In case you want to stop a loop or switch statement early, the break statement ends execution of the current for, foreach, while, do...while, or switch statement. You've already seen the break statement at work in the switch statement. Here, we're ending the code that should be executed in a case statement inside a switch statement:

 $temperature = 70; switch ($temperature):     case 70:         echo "Nice weather.";         break;         .         .         . 

You can also end loop execution early with the break statement. For example, in this loop, execution will continue five timesunless we stop things early at, say, the third loop iteration:

 <?php     for ($loop_counter = 0; $loop_counter < 5; $loop_counter++){         echo "I'm going to do this five times unless stopped!<BR>";         if ($loop_counter == 2) {         .         .         .         }     } ?> 

Here's how that might look using the break statement:

 <?php     for ($loop_counter = 0; $loop_counter < 5; $loop_counter++){         echo "I'm going to do this five times unless stopped!<BR>";         if ($loop_counter == 2) {             echo "Enough already, I'm quitting.<BR>";             break;             }     } ?> 

And this is what you see:

 I'm going to do this five times unless stopped! I'm going to do this five times unless stopped! I'm going to do this five times unless stopped! Enough already, I'm quitting. 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

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