3

I have a function that returns me the response based on the value of the input. The code is something like this

$a = 5;
switch ($a) {
    case 1: $b = 1;
    break;
    case 2 || 3 || 4: $b = 2;
    break;
    case 5: $b = 3;
    break;
}
return $b;

This returns me the value 2 instead of 3 as it can clearly be seen in code. How does this happen?

Qirel
  • 25,449
  • 7
  • 45
  • 62
Saeesh Tendulkar
  • 638
  • 12
  • 30

1 Answers1

12

You are using the cases wrong. You can't use || in the middle of a case to say 2 or 3 or 4, but you can list multiple cases after one another without having a a break in between to perform the same action.

$a = 5;

switch ($a) {
    case 1: 
        $b = 1;
        break;
    case 2:
    case 3:
    case 4: 
        $b = 2;
        break;
    case 5: 
        $b = 3;
        break;
}

return $b;

What is happening with your original code is that you get case 2 || 3 || 4 as the equivalent of case (2 || 3 || 4):, which becomes case true:. The || operator compares the truthfulness of either 2, 3 and 4 -- which all are non-zero values, so the expression evaluates to true.

You should also note that $b is undefined when $a is not one of 1, 2, 3, 4 or 5. You should therefor have a default case in your switch statement, or a declaration of $b before the switch.

Qirel
  • 25,449
  • 7
  • 45
  • 62