5

I have the following code:

<?php

echo check('three');

function check($string) {
  switch($string) {
    case 'one' || 'two' : return 'one or two'; break;
    case 'three' || 'four' : return 'three or four'; break;
  }
}

Currently it outputs:

one or two

But obviously I want the code to return three or four.

So what is right method to return the same code for multiple case statements?

0

3 Answers 3

7

Not possible. the case items must be VALUES. You have expressions, which means the expressions are evaluated, and the result of that expression is them compared against the value in the switch(). That means you've effectively got

switch(...) { 
  case TRUE: ...
  case TRUE: ...
}

You cannot use multiple values in a case. YOu can, however, use the "fallthrough support":

switch(...) {
   case 'one':
   case 'two':
       return 'one or two';
   case 'three':
   case 'four':
       return 'three or four';
 }
Sign up to request clarification or add additional context in comments.

Comments

5

Just write two case statements which execute the same code, e.g.

function check($string) {
  switch($string) {
    case 'one':
    case 'two':
        return 'one or two';
    break;

    case 'three':
    case 'four' :
        return 'three or four';
    break;
  }
}

2 Comments

I don't think you need the break statements though. The execution exits the method on the returns.
@BCartolo Yes, the return statement would end the function, but just in case you use it somewhere else where you are not in a function I just put the break; there.
1

How about using a mapping dictionary:

$oneOrTwo = 'one or two';
$threeOrFour = 'three or four';
$stringsMap = ['one' => $oneOrTwo, 'two' => $oneOrTwo, 'three' => $threeOrFour, 'four' => $threeOrFour];
return $stringsMap[$string]

Switch statements can become harder and harder to maintain if more and more values are added.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.