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;
}
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.
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.
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.
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With