开发者

Simplifing PHP or statements

Okay, I believe that I can simplify this line of code except I can't find anything online. Can anyone help me?

开发者_StackOverflow社区
if(empty($action) || $action == "a" || $action == "b" || $action == "c") {
}

Thanks!


You can use in_array() to search an array of possible values for $action:

if (empty($action) || in_array($action, array('a', 'b', 'c'))) {
}

I keep the empty() condition separate because empty() tests true for a number of things besides the empty string ''.

If all you care is to test for the empty string, you can include it in in_array(), and get rid of that empty():

if (in_array($action, array('', 'a', 'b', 'c'))) {
}

Performantly, I think explicitly including empty() is a teeny weeny little bit better, due to short-circuiting.


$options = array("a", "b", "c");
if (empty($action) || in_array($action, $options) ) {
}


I suggest you don't simplify this code because you may gain some kind of readability but you would also increase computation time. And that's a thing I would prefer to improve more than readability (code is executed a lot more often than read in plain text).

Why is that?

An expression like yours consisting only of or conjunctions will end right the moment the first 'true' value is found. So in best case PHP will just evaluate empty($action) with true and leave the if-header without evaluating all the other parts. In worst case it will check every part till the end. So in average - without further knowlege about the data you will check - you are running and computing half of the if-header.

But if you use something like in_array($action, array('a', 'b', 'c')) than you will construct the whole array with all elements and search in it. So your PHP interpreter has to create all the elements and the array just to match one of the first ones. Which is anyway more computation than your current line.

So think twice about readabilty vs. code complexity.


if (empty($action) || preg_match('/^[abc]$/', $action)) { ... }

Edit: empty($action) is needed to allow false, array(), 0, and null to pass which you may not want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜