Once switch
finds a matching case
, it just executes all the remaining code until it gets to a break
statement. None of the following case
expressions are tested, so you can’t have dependencies like this. To implement sub-cases, you should use nested switch
or if
statements.
switch ($category) {
case 'A':
$msg = 'hello';
if ($offer == 'special') {
$id = '123';
} elseif ($discount == '50D') {
$id = '999';
}
break;
...
}
echo $id;
The fallthrough feature of case
without break
is most often used when you have two cases that should do exactly the same thing. So the first one has an empty code with no break, and it just falls through.
switch ($val) {
case 'AAA':
case 'bbb':
// some code
break;
...
}
It can also be used when two cases are similar, but one of them needs some extra code run first:
switch ($val) {
case 'xxx':
echo 'xxx is obsolete, please switch to yyy';
case 'yyy':
// more code
break;
...
}
3
solved Switch/Case without a `break`, doesn’t check the cases properly