0

Possible Duplicate:
How to use a switch case 'or' in PHP?

Is it possible to have multiple conditions on single switch case for example

switch($device) {
  case 'blackberry':
  break;
  case 'iphone' || 'ipod' || 'android':
  break;
}

Thanks for the help.

Community
  • 1
  • 1
MrFoh
  • 2,693
  • 9
  • 42
  • 77

5 Answers5

6
switch($device) {
  case 'blackberry':
  break;
  case 'iphone':
  case 'ipod':
  case 'android':
  do_something();
  break;
}

As per the comment below I will elaborate a little bit.

The break statement breaks the execution of a switch statement and exits. So, if you had

case "iphone":
do_iphone();
case "ipod": 
do_ipod();
break;

(note the missing break between two cases). Both do_iphone(); and do_ipod(); will execute (in order). So, basically what we are doing is a "hack" where the engine goes to the case iphone, and executes (nothing to execute in our original case) and moves ahead to ipod and so on.

Stewie
  • 3,103
  • 2
  • 24
  • 22
  • Correct. I think you could elaborate as to why so MrDoh will understand why not having a break between the three conditions is what he's looking for. – Crashspeeder Feb 02 '12 at 14:16
3

Not with the syntax you are suggesting, you'd have to create multiple cases that point to the same action, for example:

switch($device) {
  case 'blackberry':
    blackberryFunction();
    break;
  case 'iphone':
  case 'ipod':
  case 'android':
    nonBlackberry();
    break;
}
Oldskool
  • 34,211
  • 7
  • 53
  • 66
1
switch($device) {
  case 'blackberry':
  break;
  case 'iphone':
  case 'ipod':
  case 'android':
      //handle all three here
  break;
}
Oldskool
  • 34,211
  • 7
  • 53
  • 66
Pheonix
  • 6,049
  • 6
  • 30
  • 48
0

Yes, simply use multiple case statements under one another -

switch($device){
    case 'blackberry':
    //implementation
    break;
    case 'iphone':
    case 'ipod':
    case 'android':
    //implementation
    break;
}
Hecksa
  • 2,762
  • 22
  • 34
0

Just ‘stacking’ the case statements is enough:

switch($device) {
    case 'blackberry':
        break;
    case 'iphone':
    case 'ipod':
    case 'android':
      break;
}
entropid
  • 6,130
  • 5
  • 32
  • 45