php 匹配任何 / 匹配任何等效运算符
我经常发现自己写这样的东西 if($var == 'bob' || $var == 'steven || $var == 'james'){ ...
有没有更灵活的方法在php中检查var是否与任何运算符匹配?或者我是否必须编写自己的函数,例如:
function matches_any($question, $pos_answer, $pos_answer, $pos_answer, $pos_answer, ...){
// Call the function args, get the first one, get the rest, compare all the rest, return true if any match, return false by default.
}
将这样使用:
if(matches_any($var, $bob, $steven, 'james', $william)){ ...
I frequently find myself writing things like if($var == 'bob' || $var == 'steven || $var == 'james'){ ...
Is there a slicker way in php to check whether a var matches any operator? Or do I have to write my own function like:
function matches_any($question, $pos_answer, $pos_answer, $pos_answer, $pos_answer, ...){
// Call the function args, get the first one, get the rest, compare all the rest, return true if any match, return false by default.
}
Which would be used thus:
if(matches_any($var, $bob, $steven, 'james', $william)){ ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
in_array()
You can use
in_array()
理想情况下,您应该避免将任何值硬编码到代码中 - 如果您将内容保留在数据结构中(=认为“配置”或“数据库”),您将最大限度地减少遇到此问题的机会,因为您正在处理抽象而不是比具体值。这意味着将您的概念从“这些是可以做到这一点的明确人”更改为“让我们询问另一个设施这个人是否可以做到这一点”
如果您绝对必须拥有像您所描述的那样的功能,您可以使用 func_get_args 来做到这一点():
(未经测试)
Ideally you should avoid hard-coding any values into your code -- if you keep content in data structures (=think 'config' or 'database'), you will minimize your chances for running into this problem because you're processing abstractions rather than specific values. This means changing your concept from "these are the definite people who can ever do this" into "let's ask another facility whether this guy can do this"
If you absolutely positively must have a function like what you described, you can do it with func_get_args():
(Untested)