Break is used in switch statements or inside loops. It allows program execution control to jump out of switch or loops.
Example
break with switch
<?php
$month = 3;
switch($month){
case 1:
echo "January";
break;
case 2:
echo "Feburary";
break;
case 3:
echo "March";
break;
case 4:
echo "April";
break;
case 5:
echo "May";
break;
default:
echo "December";
}
?>
In switch, when given input is matched with case label, executes related case statements and exits.
Because every case ends with break keyword and it allows to jump out of switch statement. so, that every case should not be tested and saves program execution time.
break with loops
break allows to exit loop cycle when specific condition become true. Break inside loop is used always with conditions.
<?php
for($a = 1; $a <=20; $a++)
{
if($a == 12)
{
break;
}
echo $a . ' ';
}
?>
Output:
1 2 3 4 5 6 7 8 9 10 11
Loop starts and output number from 1 to 11, As the value of $a becomes 12, the if condition becomes true and break allows to exit loop. So, loop will not output numbers from 12 to 20.
Break can be used with any loop.