0

I was wondering if there's a way to evaluate an OR in a case statement, such as:

case 0 || 3:
    echo "equal to 0 or 3!";
    break;

I tried || a little while back and it didn't seem to work for me, and a google didn't prove helpful.
I'm just wondering about this because there have been a few situations where an or operator in a case would have been very useful...
Any help is appreciated.

2 Answers 2

7

You can let cases fall through.

case 0:
case 3:
   echo "equal to 0 or 3!";
   break;

Many style guides do not recommend this.

1
  • 1
    Many style guides are wrong, then, about this specific case. In general, though, taking advantage of fallthrough makes things much harder to follow. If you have anything (without a break) in between the two cases, repent now. :)
    – cHao
    Commented Apr 26, 2012 at 3:48
1

When working with logical and comparison operators that resolve to a boolean, you can use switch(true) (or really, any "true" value, due to non-strictness of checking with switch) in circumstances where you want the first true case.

switch(true){
    case ($foo >= 0):
        break;
    case ($bar <= 0):
        break;
    case ($baz == 0):
        break;
    case ($foo > $bar && $bar < $baz):
        break;
    default:
        break;
}

However there are syntactic alternatives that may prove more readable, or provide more control.

As @alex points out, if you're looking to have multiple cases resolve to the same code block, you can stack them and let them fall through.

Not the answer you're looking for? Browse other questions tagged or ask your own question.