Is there a fast way to check if a variable belongs to a set?
I have a form and I need to check if a input belongs to enum(0,1,2,3,..,n) Is there a simpl开发者_StackOverflow中文版e way to check if my variable belongs to the set [0:n] ? Or do I have to write each condition (basically n<10, so it's feasible but not that practicle...)?
If there ain't native function to do that, could you give me a hint on how to make a function for this?
Thanks :)
You can use a combination of range()
and in_array()
.
Example:
$number = 5;
$set = range(0, 10);
if (in_array($number, $set))
{
//
}
$set = range(0,n);
if (in_array ($value, $set)) {
print "IS IN ARRAY!";
}
This is true for range from 0 to n If you want to make specific range. f.e. 0,1,3,7, you can use
$set = array(0,1,3,7...);
You could make the range and run in_array, but that probably wouldn't be great for performance. PHP would internally end up looping through the numbers you provided to create a brand new (potentially huge) array, and then loop through the array all over again to see if X is in there somewhere. That's a lot more work than necessary for a simple "is it within these numbers" check.
Sticking to the two conditions is probably the best way to go, especially since it'd be much more readable. You can also make a helper function if this is, for some reason, really getting to you.
function is_within_inclusive($x, $start, $end) {
return $x >= $start && $x <= $end;
}
But if you already have the range defined, anyway, for other reasons, in_array seems fine.
精彩评论