There's filter_var()
as well and it's the native function which checks range. It doesn't give exactly what you want (never returns true), but with "cheat" we can change it.
I don't think it's a good code as for readability, but I show it's as a possibility:
return (filter_var($someNumber, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]]) !== false)
Just fill $someNumber
, $min
and $max
. filter_var
with that filter returns either boolean false when number is outside range or the number itself when it's within range. The expression (!== false
) makes function return true, when number is within range.
If you want to shorten it somehow, remember about type casting. If you would use !=
it would be false for number 0 within range -5; +5 (while it should be true). The same would happen if you would use type casting ((bool)
).
// EXAMPLE OF WRONG USE, GIVES WRONG RESULTS WITH "0"
(bool)filter_var($someNumber, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]])
if (filter_var($someNumber, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]])) ...
Imagine that (from other answer):
if(in_array($userScore, range(-5, 5))) echo 'your score is correct'; else echo 'incorrect, enter again';
If user would write empty value ($userScore = ''
) it would be correct, as in_array
is set here for default, non-strict more and that means that range creates 0
as well, and '' == 0
(non-strict), but '' !== 0
(if you would use strict mode). It's easy to miss such things and that's why I wrote a bit about that. I was learned that strict operators are default, and programmer could use non-strict only in special cases. I think it's a good lesson. Most examples here would fail in some cases because non-strict checking.
Still I like filter_var and you can use above (or below if I'd got so "upped" ;)) functions and make your own callback which you would use as FILTER_CALLBACK
filter. You could return bool or even add openRange
parameter. And other good point: you can use other functions, e.g. checking range of every number of array or POST/GET values. That's really powerful tool.