'Can a switch statement take two arguments?

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!

php


Solution 1:[1]

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.

Solution 2:[2]

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

Solution 3:[3]

i have the answer ! You can do that by remove the "break" instruction. if you do

$i = 2;
switch ($i) {
    case 1:
        echo "a";
        break;
    case 2:
        echo 'b';
        break;
    case 2:
        echo 'c';
        break;
    case 3:
        echo 'd';
        break;
}

Your script will stop at the first break. So the output is b.

Now, if you remove the break instruction, the switch will continue to the end and verify all.

$i = 2;
switch ($i) {
    case 1:
        echo "a";
        break;
    case 2:
        echo 'b';
    case 2:
        echo 'c';
        break;
    case 3:
        echo 'd';
        break;
}

Output : cb So you can do 2 conditionnal instruction like this :

$i = 3;
switch ($i) {
    case 1:
        echo "a";
        break;
    case 2:
    case 3:
        echo 'd';
        break;
}

Output: d Your computer will read the case 2: and the result it false, but there is no break instruction, so the computer will continue and read case 3: >> True and the result is true : the computer execute your instruction. :)

If you didn't understand my explanation, i own you to read the switch php manual here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KingCrunch
Solution 2 Oscar Gomez
Solution 3 Eric Aya