tags:

views:

257

answers:

7

Is it possible to use three parameters in switch-case, like this:

switch($var1, $var2, $var3){
    case true, false, false:
        echo "Hello";
        break;
}

If not, should I just use if-else or is there a better solution?

A: 

i don't think your syntax is valid.

I'd nest the switch statements.

mson
that would be a lot of nesting with multiple similar switches ?
OIS
+3  A: 

You don't have a switch situation here. You have a multiple condition:

if($var && !($var2 || $var3)) { ...
dnagirl
That also matches true, false, true etc.
Tom Haigh
You could make the sub-clause in brackets an OR (||) instead
Tom Haigh
fixed with the ||. Thanks for catching the typo!
dnagirl
+2  A: 

I would just use the if/else

if($var1 == true && $var2 == false && $var3 == false){
    echo "Hello";
}

or

if($var1 && !($var2 && $var3)) {
    echo "Hello";
}
jasondavis
A: 

I don't know - if you really want it this way - maybe cast them all to string, concatenate and then use the resulting string in your case condition?

DmitryK
+12  A: 

The syntax is not correct and I wouldn't recommend it, even if it was. But if you really want to use a construct like that, you can put your values into an array:

switch (array($var1, $var2, $var3)) {
    case array(true, false, false):
        echo "hello";
        break;
}
soulmerge
Thanks a lot :)
Johan
wow, I had no idea this works, and I'm somewhat frightened that it does.
rmeador
I think it's best for all of us to forget that it does.
soulmerge
+1  A: 

Another option is to create a function that maps three parameters to an integer and use that in the switch statement.

function MapBool($var1, $var2, $var3){
    // ...
}

switch(MapBool($var1, $var2, $var3)) {
    case 0: 
        echo "Hello";
        break;
   // ...

}
Gamecat
Similar to Alex Feinman answer I suppose, without explaining how though.
OIS
Not exactly. You can do anything with the function. But accepting the booleans as bits of a 3 bit byte is the most logical implementation, yes.
Gamecat
+1  A: 

This is the sort of thing that used to be handled by bitwise operators:

if (($var1 << 2) & ($var2 << 1) & $var3) == 4) ...

...back when 'true' was 1.

That being said, the above is concise, but it's pretty hard to read and maintain. Nevertheless, if you have a lot of similar statements, shifting/ANDing might be a way to go to get things under control:

switch (($var1 << 2) & ($var2 << 1) & $var3)) {
   case 0: // false, false, false
       ...stuff...
   case 1: // false, false, true
       ...different stuff...
   // all 8 cases if you REALLY care
}
Alex Feinman