Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 526
tolborg Avatar asked Aug 25 '26 18:08

tolborg


1 Answers

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.

like image 158
deceze Avatar answered Aug 28 '26 09:08

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!