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?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Dmitriy K
  • 177
  • 1
  • 4
  • 11

3 Answers3

6

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';
 }
Marc B
  • 356,200
  • 43
  • 426
  • 500
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;
  }
}
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • I don't think you need the break statements though. The execution exits the method on the returns. – BCartolo Jan 08 '16 at 16:05
  • @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. – Rizier123 Jan 08 '16 at 16:06
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.

Cristik
  • 30,989
  • 25
  • 91
  • 127