PHP switch case 中多个值的情况

2022-01-19 00:00:00 switch-statement php case

我有一个变量保存值每周"、每月"、季度"和年度",我还有另一个变量保存从 1 到 10 的值.

I have a variable that holds the values 'Weekly', 'Monthly', 'Quarterly', and 'Annual', and I have another variable that holds the values from 1 to 10.

switch ($var2) {
    case 1:
        $var3 = 'Weekly';
        break;
    case 2:
        $var3 = 'Weekly';
        break;
    case 3:
        $var3 = 'Monthly';
        break;
    case 4:
        $var3 = 'Quarterly';
        break;
    case 5:
        $var3 = 'Quarterly';
        break;
    // etc.
}

它并不漂亮,因为我的代码有很多重复项.我想要什么:

It isn't beautiful, because my code has a lot of duplicates. What I want:

switch ($var2) {
    case 1, 2:
        $var3 = 'Weekly';
        break;
    case 3:
        $var3 = 'Monthly';
        break;
    case 4, 5:
        $var3 = 'Quarterly';
        break;
}

我如何在 PHP 中做到这一点?

How can I do it in PHP?

推荐答案

性能方面最简单也可能是最好的方法是:

The simplest and probably the best way performance-wise would be:

switch ($var2) {
    case 1:
    case 2:
       $var3 = 'Weekly';
       break;
    case 3:
       $var3 = 'Monthly';
       break;
    case 4:
    case 5:
       $var3 = 'Quarterly';
       break;
}

此外,可能适用于更复杂的情况:

Also, possible for more complex situations:

switch ($var2) {
    case ($var2 == 1 || $var2 == 2):
        $var3 = 'Weekly';
        break;
    case 3:
        $var3 = 'Monthly';
        break;
    case ($var2 == 4 || $var2 == 5):
        $var3 = 'Quarterly';
        break;
}

在这种情况下,$var2 必须设置,不能为 null 或 0

In this scenario, $var2 must be set and can not be null or 0

相关文章