PHP break is a keyword use with mostly for, do-while, while and switch structure.
PHP break ends execution of current loop.
break keyword can accept numeric arguments. By default value is 1. It will enclose only one immediate structure.
For example:
break 1 or break – It ends execution of one loop.
break 2 – It ends execution of 2 loops.
Note: From PHP5.4.0, break 0; is no longer valid.
In previous versions it was interpreted the same as break 1;
Example
1 2 3 4 5 6 7 8 9 10 |
<?php $a = 0; while($a < 10) { echo "a = $a"; break; //can also write break 1; } ?> |
Output:
1 |
a = 0 |
In above example you can see only one value of a is print because of break.
break ends the current loop.
Due to break only one time condition is checked and one time loop is executed.
If there will not any break then loop will execute 10 times.
PHP break with switch structure:
We see the use of break in switch structure chapter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php $m = 6; switch ($m) { case 1: echo "You born in January"; break; case 2: echo "You born in February"; break; case 3: echo "You born in March"; break; case 4: echo "You born in April"; break; case 5: echo "You born in May"; break; case 6: echo "You born in June"; break; case 7: echo "You born in July"; break; case 8: echo "You born in August"; break; case 9: echo "You born in September"; break; case 10: echo "You born in October"; break; case 11: echo "You born in November"; break; case 12: echo "You born in December"; break; default: echo "Please enter valid month number"; } ?> |
Output
1 |
You born in June |
break with arguments
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php $a = 0; while($a < 10) { switch($a) { case 0: echo "Number 0<br>"; case 1: echo "Number 1<br>"; case 2: echo "Number 2<br>"; break 1; //Exit only the switch. case 3: echo "Number 3<br>"; break 2; //Exit the switch and the while. case 4: echo "Number 4"; } $a++; } ?> |
Output
1 2 3 4 5 6 7 |
Number 0 Number 1 Number 2 Number 1 Number 2 Number 2 Number 3 |
Now understand how break work in switch structure.
There are 2 loops, outer loop while and inner loop switch.
At beginning, at $a = 0; both while and switch condition is true.
Therefore it print statements of case having matching case value i.e. Number 0.
But after matching case 0, there is no break so it print next statements upto break.
AS you can see in output when $a = 0, it print Number 0, Number 1, Number 2.
break 1 results termination of switch and increment $a by 1.
In this way, when $a = 1 and $a = 2, it will print respected matching case statements.
When $a = 3, only “Number 3” is print and it break the execution of both switch and while loop due to break argument 2.