Switch/Case without a `break`, doesn't check the cases properly
I'm having trouble with a switch case conidtion.
Why in the following scenario:
$category = "A";
$offer = "none";
$discount = "none";
For the following code:
switch (TRUE) {
case ($category == 'A') : / #1
$msg = "hello";
case ($offer == 'special') : / #2
$id = "123";
case ($discount == '50D') : / #3
$id = "999";
break;
echo $id;
}
I get output of 999
for id
, even though #2
and #3
are not fullfilled?
EDIT:
Cases such as $offer == 'special'
are private cases of the general case which is $category == 'A'
. That's why I want the function to go in this order. if switch/case is not appropriate, what shall I use?
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;
...
}
This is how a switch-case statement works. It goes through all the case
es once one condition was met, as long as there is no break. You can read up on it in the manual here: PHP switch.
If you want to stop the execution of the switch at the end of an case, just add a break;
statement.
上一篇: 为什么交换声明需要休息?