在 PHP 中比较多个值
我想从这个:
if($var == 3 || $var == 4 || $var == 5 || $var =='string' || $var == '2010-05-16') {
// execute code here
}
到这个:
if($var == (3, 4, 5, 'string', '2010-05-16')) { // execute code here }
继续输入 $var
似乎非常多余,而且我发现这使得阅读起来有点麻烦。 PHP 有没有办法以这种方式简化它?我在这里读到一篇文章,当使用 XQuery 时,您可以使用 = 运算符,如 $var = (1,2,3,4,5)
等。
I'd like to go from this:
if($var == 3 || $var == 4 || $var == 5 || $var =='string' || $var == '2010-05-16') {
// execute code here
}
to this:
if($var == (3, 4, 5, 'string', '2010-05-16')) { // execute code here }
Seems very redundant to keep typing $var
, and I find that it makes it a bit cumbersome to read. Is there a way in PHP to do simplify it in this way? I read on a post here that when using XQuery you can use the = operator as in $var = (1,2,3,4,5)
etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
将值放入数组中,然后使用函数 in_array() 检查它们是否存在。
http://uk.php.net/manual/en/function.in -array.php
Place the values in an array, then use the function in_array() to check if they exist.
http://uk.php.net/manual/en/function.in-array.php
如果您需要经常执行此检查并且需要良好的性能,请不要使用慢速数组搜索,而应使用快速哈希表查找:
If you need to perform this check very often and you need good performance, don't use a slow array search but use a fast hash table lookup instead:
或者,也可以使用开关块:
Or, alternatively, a switch block:
您可以使用
in_array()
。You can use
in_array()
.或者您可以使用
in_array()
Or you can use
in_array()
只是为了提供使用
in_array
的替代解决方案:在某些情况下,设置一个以值为键的数组,然后使用
isset()
进行检查可能会更快:
编辑:我已经做了一些测试,看起来这种方法在大多数情况下更快。
Just to give an alternative solution to the use of
in_array
:In some cases it could be faster to set an array where the values are keys and then check with
isset()
Example:
EDIT: I have done some testing and it looks like this method is faster in most cases.
我遇到了这个问题并通过创建这个函数解决了它:
然后你可以像这样调用该函数:
I've had this problem and solved it by making this function:
then you can just call the function like this: