php matches any / match any operator equivalent
I frequently find myself writing things like if($var == 'bob' || $var == 'steven || $var == 'james'){ ...
Is there开发者_如何学JAVA 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)){ ...
You can use in_array()
if(in_array('value_to_test', array($var, $bob, $steven, 'james', $william))) {}
$matches = array($var, $bob, $steven, 'james', $william);
if (in_array('james', $matches)) {
// TRUE
}
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():
function matches_any()
{
$haystack = func_get_args();
$needle = array_shift( $haystack );
return in_array( $needle, $haystack );
}
(Untested)
精彩评论