Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
771 views
in Technique[技术] by (71.8m points)

php - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...