views:

5991

answers:

5

is there such thing (in PHP anyway) for an OR operator in a switch case?

something like..

switch ($value) {

case 1 || 2:
echo 'the value is either 1 or 2';
break;

}
+31  A: 
switch ($value)
{
    case 1:
    case 2:
        echo "the value is either 1 or 2.";
    break;
}

This is called "falling though" the case block and it exists in most languages which implement a switch statement.

nlaq
To be pedantic some languages like C# do not "fall through" but rather allow a set of case labels at the top of a block of code. True fall-through allows code between the cases.
BCS
Ah, you are right of course. But it's almost the same idea :)
nlaq
The only thing I'd change is to add a comment after case 1 indicating that falling through is what you intended.
Keith Twombley
+4  A: 

Try

switch($value) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}
Craig
A: 

ah i see, so as long as i order them in the right fashion I can achieve this? excellent, and once again thank you!

Since you asked the question you can mark a reply as the best answer to help future readers.
Keith Twombley
+6  A: 

I won't repost the other answers because they're all correct, but I'll just add that you can't use switch for more "complicated" statements, eg: to test if a value is "greater than 3", "between 4 and 6", etc. If you need to do something like that, stick to using if statements, or if there's a particularly strong need for switch then it's possible to use it back to front:

switch (true) {
    case ($value > 3) :
        // value is greater than 3
    break;
    case ($value >= 4 && $value <= 6) :
        // value is between 4 and 6
    break;
}

but as I said, I'd personally use an if statement there.

nickf
Glad to see that you recommended if() over switch() in this case. This kind of switch just adds complexity, IMO.
orlandu63
yeah, you'd have to have a fairly compelling reason to choose this style, but it's good to know that it's possible.
nickf
I'm actually glad to have learned this. Every time I build a project in a Basic-y language, I miss having a C-style `switch()`, and when I'm working in a C-ish language I really miss having `Select Case`, which is really a shorthand way of saying "there's a big block of if, else if, else-if... here".
Stan Rogers
A: 

Thanks so much (y)

Neo