Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a switch statement take two arguments?

Tags:

php

is it posible for a PHP switch statement to take 2 arguements? For example:

switch (firstVal, secondVal){

    case firstVal == "YN" && secondVal == "NN":
    thisDesc = "this is the outcome: YN and NN";
    break;

    case firstVal == "YY" && secondVal == "NN":
    thisDesc = "this is the outcome: YY and NN";
    break;
}

Many thanks, I haven't done PHP in years!

like image 519
Mike Sav Avatar asked Jul 05 '11 19:07

Mike Sav


3 Answers

No, you can't. A switch-statement like

switch ($a) {
  case 1:
  break;
  case 2:
  break;
}

which is effectively the same as

if ($a == 1) {
} else if ($a == 2) {
}

You can use a slightly different construction

switch (true) {
  case $firstVal == "YN" && $secondVal == "NN":
  break;
  case $firstVal == "YY" && $secondVal == "NN":
  break;
}

which is equivalent to

if (true == ($firstVal == "YN" && $secondVal == "NN")) {
} else if (true == ($firstVal == "YY" && $secondVal == "NN")) {
}

In some cases its much more readable instead of infinite if-elseif-else-chains.

like image 158
KingCrunch Avatar answered Sep 30 '22 01:09

KingCrunch


No, but if your case is as simple as what you have, just concatenate the two inputs and test for the concatenated values:

switch ($firstval . $secondval) {
 case "YNNN": ...
 case "YYNN": ...
}
like image 28
Mat Avatar answered Sep 30 '22 01:09

Mat


Old question, but i think this answer is not covered here:

You can pass multiple arguments to an array and pass that as the argument to the switch:

switch([$fooBah, $bool]) {
            case ['foo', true]:
                ...
                break;
            case ['foo', false]:
            case ['bah', true]:
                ...
                break;
            case ['bah', false]:
                ...
                break;
            ...
        }
like image 38
Steffen Avatar answered Sep 30 '22 01:09

Steffen