-1

In the switch statement, when i have a case with "||" it doesn't work properly.

$get = 'item';
switch ($get):

case 'items' || 'several-items':
    echo 'items';
    break;

case 'item':
    echo 'item';
    break;

endswitch;

This code outputs items. Is this a php bug ?

$get = 'several'; outputs items too.

So the problem is definitely with the '||' operator, because the following code works just fine:

$get = 'item';
switch ($get):

case 'items':
case 'several-items':
    echo 'items';
    break;

case 'item':
    echo 'item';
    break;

endswitch;
Andrei Telteu
  • 191
  • 2
  • 8

2 Answers2

2

You can't use OR (||) and AND (&&) operators in a switch statement

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
0

Then use

case 'items':
case 'several-items':
    echo 'items';
    break;

instead, especially as that is the documented method to use

otherwise you're testing against a case of the logical or of 'items' and 'several-items' (because || will always have the precedence), which is a boolean false; and your $get value will match that Boolean false unless it loose casts to a truthy value (ie is 1item or similar)

Mark Baker
  • 209,507
  • 32
  • 346
  • 385