Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch statement with two variables at a time

Tags:

Could someone suggest the best way to have the following switch statement? I don't know that it's possible to compare two values at once, but this would be ideal:

switch($color,$size){
    case "blue","small":
        echo "blue and small";
    break;

    case "red","large";
        echo "red and large";
    break;
}

This could be comparable to:
if (($color == "blue") && ($size == "small")) {
    echo "blue and small";
}
elseif (($color == "red") && ($size == "large")) {
    echo "red and large";
}

Update I realized that I'll need to be able to negate ($color !== "blue") and compare as opposed to equating variables to strings.

like image 540
d-_-b Avatar asked Sep 26 '12 04:09

d-_-b


People also ask

Can a switch statement have two variables?

Use a case/switch statement with two variables This code executes the switch statement, pretty much just like if/else but looks cleaner. It will continue checking your variables in the case expressions. Do comment if you have any doubts or suggestions on this JS switch case topic.

Can we pass multiple values in switch case?

Here is some important point of the switch statement in Java, have to follow. You can use N number of case values for a switch expression. The Case unit must be unique, otherwise, a compile-time error occurred. The default case is optional.


2 Answers

Using the new array syntax, this looks almost like what you want:

switch ([$color, $size]) {
    case ['blue', 'small']:
        echo 'blue and small';
    break;

    case ['red', 'large'];
        echo 'red and large';
    break;
}
like image 112
Renaat De Muynck Avatar answered Sep 19 '22 15:09

Renaat De Muynck


You can change the order of the comparison, but this is still not ideal.

    switch(true)
    {
      case ($color == 'blue' and $size == 'small'):
        echo "blue and small";
        break;
      case ($color == 'red' and $size == 'large'):
        echo "red and large";
        break;
      default:
        echo 'nothing';
        break;
    }
like image 34
Scuzzy Avatar answered Sep 20 '22 15:09

Scuzzy