How to check if an integer is within a range of numbers in PHP?
You can use filter_var
filter_var(
$yourInteger,
FILTER_VALIDATE_INT,
array(
'options' => array(
'min_range' => $min,
'max_range' => $max
)
)
);
This will also allow you to specify whether you want to allow octal and hex notation of integers. Note that the function is type-safe. 5.5
is not an integer but a float and will not validate.
Detailed tutorial about filtering data with PHP:
- https://phpro.org/tutorials/Filtering-Data-with-PHP.html
The expression:
($min <= $value) && ($value <= $max)
will be true if $value
is between $min
and $max
, inclusively
See the PHP docs for more on comparison operators