Optionality of Break in PHP
The break
command is optional.
However, without it, the behavior of the case
blocks
will be unexpected. Let's look at an example.
Suppose we have the following code:
<?php
$num = 1;
switch ($num) {
case 1:
echo 1;
break;
case 2:
echo 2;
break;
case 3:
echo 3;
break;
}
?>
Let's remove all break
from it, and to start,
let's assign the number 3
to the variable $num
.
For now, everything will work as it did:
<?php
$num = 3; // let the number be 3 here
switch ($num) {
case 1:
echo 1;
case 2:
echo 2;
case 3:
echo 3;
}
// After running, the code will output 3 - all good
?>
Now let's assign the number 2
to the variable $num
.
In this case, case 2
will execute as expected,
and then, unexpectedly, case 3
will also execute:
<?php
$num = 2;
switch ($num) {
case 1:
echo 1;
case 2:
echo 2;
case 3:
echo 3;
}
// After running, the code will output 2, and then 3
?>
If we assign the number 1
to the variable $num
,
then all case
constructs will execute:
<?php
$num = 1;
switch ($num) {
case 1:
echo 1;
case 2:
echo 2;
case 3:
echo 3;
}
// After running, the code will output 1, then 2, and then 3
?>
So it turns out that in the absence of break
,
after the intended case
is executed,
all case
blocks below it will also execute. Sometimes
this feature is used when solving problems.
In the next example, if the variable $num
has the value 1
or 2
, then
the value 'a'
will be assigned to the variable $res
.
If the variable $num
has the value
3
, then the value 'b'
will be
assigned to the variable $res
:
<?php
$num = 1;
switch ($num) {
case 1:
case 2:
$res = 'a';
break;
case 3:
$res = 'b';
break;
}
echo $res;
?>
Above I wrote that sometimes this feature is used, but I, generally speaking, do not recommend using it, as the code becomes not very obvious.
It is more obvious to solve such a problem with ifs:
<?php
$num = 1;
if ($num == 1 or $num == 2) {
$res = 'a';
}
if ($num == 3) {
$res = 'b';
}
echo $res;
?>