Switch statement with multiple cases that execute the same code

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

He currently issues:

one or two

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

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

+4
source share
3 answers

Impossible. items casemust be VALUES . You have expressions, which means that the expressions are evaluated, and the result of this expression is compared with the value in switch(). This means that you have effectively received

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

You cannot use multiple values ​​in the case. However, you can use the "failure of support":

switch(...) {
   case 'one':
   case 'two':
       return 'one or two';
   case 'three':
   case 'four':
       return 'three or four';
 }
+2

case, , .

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

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

:

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

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

+1
source

Source: https://habr.com/ru/post/1623446/


All Articles