简化操作,例如:if($ variable == 1 || $ variable ==“随便什么" || $ variable =='492'). [英] Short hand to do something like: if($variable == 1 || $variable == "whatever" || $variable == '492') .
问题描述
我发现自己正在执行这种类型的IF
语句分配.例如:
I find my self doing this type of IF
statement allot. For example:
if($variable == 1 || $variable == "whatever" || $variable == '492') { ... }
除了时间分配外,我将$ variable与4-5件事进行比较,有时还会更多.有写这个的简便方法吗?您会看到重复$variable ==
将变得多余.
Except for allot of the time, I am comparing the $variable to maybe 4-5 things, sometimes more. Is there a short hand way to write this? You can see that repeating $variable ==
would get redundant.
我希望它能正常工作,但事实并非如此:
I would love for this to work, but it doesn't:
if($variable == (1 || "whatever" || 492) { ... }
推荐答案
您可以使用此速记形式,但请记住,使用or子句显式列出它们全部的效率较低:
You can use this shorthand, but keep in mind that it is less efficient that explicitly listing them all with or clauses:
if(in_array($variable, array(1, 'whatever', '492'))){ ... }
此外,如果要使用===
而不是==
,则等效项是:
Also if you want to use ===
instead of ==
the equivalent is:
if(in_array($variable, array(1, 'whatever', '492'), TRUE)){ ... }
这篇关于简化操作,例如:if($ variable == 1 || $ variable ==“随便什么" || $ variable =='492').的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!