Can a switch statement accept two arguments?

Is it possible for the PHP switch statement to take two arguments? For instance:

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;
}

Thank you very much, I have not done PHP for many years!

+5
source share
3 answers

No, but if your case is as simple as yours, just connect the two inputs and check the concatenated values:

switch ($firstval . $secondval) {
 case "YNNN": ...
 case "YYNN": ...
}
+2
source

No, you can’t. A is a switchvalue of type

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

which actually matches

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

You can use a slightly different design

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

which is equivalent

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

In some cases its much more readable than the infinite- if-elseif-elsechain.

+6
source

I am sure that you cannot do this, not only in PHP, but also in any other programming language.

0
source

All Articles