[英]Should I use nested if .. else statements for a series of less than comparisons in PHP
I need to do a series of comparisons with an integer in PHP, returning a different string depending on the result and I am wondering if an if..else block is the most elegant method. 我需要与PHP中的整数进行一系列比较,根据结果返回不同的字符串,我想知道if..else块是否是最优雅的方法。 The code looks like:
代码如下:
if( $total < 10000 ) {
return 'string A';
} elseif( $total < 20000 ) {
return 'string B';
} elseif( $total < 30000 ) {
return 'string C';
} elseif( $total < 40000 ) {
return 'string D';
} elseif( $total < 50000 ) {
return 'string E';
}
Which works, I just don't think it's very pretty. 哪个有效,我觉得它不是很漂亮。 If I was doing equality checks then I would use a switch block.
如果我正在进行等式检查,那么我会使用一个开关块。
You could use an array like this (assuming that $total
is always positive): 你可以使用这样的数组(假设
$total
总是正数):
$results = array('string A', 'string B', 'string C', 'string D', 'string E');
$index = floor($total / 10000);
if ($index < 5) return $results[$index];
If you want to use a switch-case statement as suggested in one of the comments you will have to write it like this: 如果你想使用其中一条评论中建议的switch-case语句,你必须像这样写:
switch(true) {
case ($total < 10000): return 'string A';
case ($total < 20000): return 'string B';
case ($total < 30000): return 'string C';
case ($total < 40000): return 'string D';
case ($total < 50000): return 'string E';
}
Each case will be evaluated as true|false, and as soon as you script hits what it is looking for true
it will return the corresponding string. 每个案例将被评估为真|虚假的,并且只要你的脚本打它正在寻找
true
将返回相应的字符串。
It will probably not be more efficient than your original code, but it is easier to read... 它可能不会比原始代码更有效,但它更容易阅读...
You could use a switch statement like: 您可以使用如下的switch语句:
switch (round($total / 10000)) {
case 0: //0xxxx
break;
case 1: //1xxxx
break;
case 2: //2xxxx
break;
case 3: //3xxxx
break;
...
}
I'm not a PHP programmer so syntax may be wrong. 我不是PHP程序员,所以语法可能是错误的。
您还可以查看责任链模式 ,尽管这可能对您的UseCase有些过分。
From the code-reusing pov, op's style is quite satisfactory. 从代码重用pov开始,op的风格非常令人满意。 It's easy to comprehend and modify.
它很容易理解和修改。 But, yeah, for "elegance", Gumbo's snippet is the way to go.
但是,是的,对于“优雅”,Gumbo的代码片段是要走的路。
if ($total < 10000) { return 'string A'; }
elseif ($total < 20000) { return 'string B'; }
elseif ($total < 30000) { return 'string C'; }
elseif ($total < 40000) { return 'string D'; }
elseif ($total < 50000) { return 'string E'; }
This wouldn't work in cases where you are not returning based on the result, or when you need to do more than one operation, but with the example you provided, you wouldn't even need the else if's or a switch, it could just be: 如果您没有根据结果返回,或者您需要执行多个操作,这不起作用,但是根据您提供的示例,您甚至不需要其他if或者切换,它可以只是:
if ($total < 10000) return 'A';
if ($total < 20000) return 'B';
if ($total < 30000) return 'C';
if ($total < 40000) return 'D';
if ($total < 50000) return 'E';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.