How to use a switch case 'or' in PHP

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.


If you must use || with switch then you can try :

$v = 1;
switch (true) {
    case ($v == 1 || $v == 2):
        echo 'the value is either 1 or 2';
        break;
}

If not your preferred solution would have been

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

The issue is that both method is not efficient when dealing with large cases ... imagine 1 to 100 this would work perfectly

$r1 = range(1, 100);
$r2 = range(100, 200);
$v = 76;
switch (true) {
    case in_array($v, $r1) :
        echo 'the value is in range 1 to 100';
        break;
    case in_array($v, $r2) :
        echo 'the value is in range 100 to 200';
        break;
}

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.