How to use a switch case 'or' in PHP

Viewed 315166

Is there a way of using an 'OR' operator or equivalent in a PHP switch?

For example, something like this:

switch ($value) {

    case 1 || 2:
        echo 'the value is either 1 or 2';
        break;
}
12 Answers
switch ($value)
{
    case 1:
    case 2:
        echo "the value is either 1 or 2.";
    break;
}

This is called "falling through" the case block. The term exists in most languages implementing a switch statement.

I won't repost the other answers because they're all correct, but I'll just add that you can't use switch for more "complicated" statements, eg: to test if a value is "greater than 3", "between 4 and 6", etc. If you need to do something like that, stick to using if statements, or if there's a particularly strong need for switch then it's possible to use it back to front:

switch (true) {
    case ($value > 3) :
        // value is greater than 3
    break;
    case ($value >= 4 && $value <= 6) :
        // value is between 4 and 6
    break;
}

but as I said, I'd personally use an if statement there.

Try

switch($value) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

Match expression (PHP 8)

PHP 8 introduced a new match expression that is similar to switch but with the shorter syntax and these differences:

  • doesn't require break statements
  • combine conditions using a comma
  • returns a value
  • has strict type comparisons
  • requires the comparison to be exhaustive (if no match is found, a UnhandledMatchError will be thrown)

Example:

match ($value) {
  0 => '0',
  1, 2 => "1 or 2",
  default => "3",
}

Note that you can also use a closure to assign the result of a switch (using early returns) to a variable:

$otherVar = (static function($value) {
    switch ($value) {
        case 0:
            return 4;
        case 1:
            return 6;
        case 2:
        case 3:
            return 5;
        default:
            return null;
    }
})($i);

Of course this way to do is obsolete as it is exactly the purpose of the new PHP 8 match function as indicated in _dom93 answer.

Related