Problem statement: Given an integer, check if that integer is within the given range.
Example 1
num=5
, range=[3,10]
true
Example 2
num=12
, range=[3,10]
false
filter_var()
functionThe filter_var()
function in PHP is used to validate/filter a variable according to the specified filter.
filter_var(var, filtername, options)
var
: The variable to be evaluated.filtername
: The name of the filter to use. This is an optional parameter.options
: Flags/options to use. This is an optional parameter.The method returns the filtered data on successful. Otherwise, it returns false
on failure.
FILTER_VALIDATE_INT
filterThe FILTER_VALIDATE_INT
filter is used to check if the value is an integer. The filter optionally accepts a range when specified checks if the given integer value is within the range.
The options to specify for range check are as follows:
min_range
: This specifies the minimum value in the integer range.max_range
: This specifies the maximum value in the integer range.By combining filter_var()
and FILTER_VALIDATE_INT
, we can check if the given number is within the given range.
<?php$range = array('min_range' => 3, 'max_range' => 10,);$options = array('options' => $range);$num = 7;if (filter_var($num, FILTER_VALIDATE_INT, $options) == false){echo $num." is not in range ";print_r($range);} else{echo $num." is in range ";print_r($range);}?>
filter_var()
function and the FILTER_VALIDATE_INT
filter. Depending on the result, we print a string.Free Resources