本文介绍了PHP switch 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
这篇关于PHP switch case 中多个值的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!