简体   繁体   中英

PHP switch statement with same value in multiple cases

I really like the structure of the switch statement compared to using multiple if else. However some times I want to use the switch statement and have the same value in multiple cases. Can this be done somehow?

switch($fruit) {
  case 'apple':
  case 'orange':
    // do something for both apples and oranges
    break;

  case: 'apple':
    // do something for only apples
    break;

  case: 'orange':
    // do something for only oranges
    break;
}

I hope my example show what I intend to do...

No, it cannot. The first case that matches and everything following it until the first break statement or the end of the switch statement will be executed. If you break , you break out of the switch statement and cannot re-enter it. The best you could do is:

switch ($fruit) {
    case 'apple':
    case 'orange':
        ...

        switch ($fruit) {
            case 'apple':
                ...
            case 'orange':
                ...
        }
}

But really, don't. If you need some special action for those two before the individual switch , do an if (in_array($fruit, ['apple', 'orange'])) ... before the switch . Or rethink your entire program logic and structure to begin with.

Create some function and do it like this:

switch($fruit) {

  case: 'apple':
    apple_and_orange_function();
    apple_function();
    break;

  case: 'orange':
    apple_and_orange_function();
    orange_function();
    break;
}

You cannot match something multiple times, but you can write cascades like these:

switch($fruit) {
  case 'apple':
    // do something for only apples
  case 'orange':
    // do something for both apples and oranges
    break;
  case: 'grapefruit':
    // do something for only grapefruits
    break;
}

What you want can only be performed with if-else's or deceze's solution though

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM