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. |