PHP切换大小写的情况下多个值 [英] PHP switch case more than one value in the case

查看:55
本文介绍了PHP切换大小写的情况下多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,其值分别为每周",每月",季度"和年度",另外还有一个变量,其值从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

这篇关于PHP切换大小写的情况下多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆