Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch statement with multiple cases which 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;
  }
}

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?

like image 930
Dmitriy K Avatar asked Jan 08 '16 16:01

Dmitriy K


2 Answers

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';
 }
like image 86
Marc B Avatar answered Sep 21 '22 11:09

Marc B


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;
  }
}
like image 33
Rizier123 Avatar answered Sep 21 '22 11:09

Rizier123