switch statement with multiple cases which execute

2019-02-18 02:34发布

问题:

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?

回答1:

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


回答2:

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


回答3:

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.