如何在 PHP 中使用开关大小写“or”

2022-08-30 06:11:39

有没有办法在PHP交换机中使用“OR”运算符或等效项?

例如,像这样:

switch ($value) {

    case 1 || 2:
        echo 'the value is either 1 or 2';
        break;
}

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

这称为“掉落”案例块。该术语存在于实现 switch 语句的大多数语言中。


答案 2

如果你必须使用,那么你可以试试:||switch

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

如果不是,您的首选解决方案将是

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

问题是,在处理大案子时,这两种方法都效率不高......想象一下,这将完美地工作1100

$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;
}

推荐