3

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

7
  • @tastro he just wants a case that will run if its apple OR orange, and then a case that will run for each individually. Commented Jul 17, 2014 at 14:26
  • The only way I can think of this is multiple switches, one for the ORs, and one for the Singulars Commented Jul 17, 2014 at 14:27
  • Other than nesting another switch inside the first one to address each special case, you would just need an if() inside it. Commented Jul 17, 2014 at 14:27
  • You could use the switch(true) functionality for the switch style layout. programmersnotes.info/2009/03/06/trick-with-php-switch Commented Jul 17, 2014 at 14:27
  • @t3chguy can you elaborate on this in relation to my example? Commented Jul 17, 2014 at 14:29

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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;
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.