Hello friends,
Today we will discuss how to validate an integer within a range. In PHP, filter_var() function is used for this purpose. It will check whether an integer exist within a range or not.
Syntax:
filter_var(var, filtername, options)
var: var is a variable name that we need to check. It is a required parameter.
filtername: It is the name of the filter which is by default FILTER_DEFAULT that is no filtering. It is an optional parameter. In this case, we will use FILTER_VALIDATE_INT which is used to validate an integer.
options: options must be defined as an associative multidimensional array named as options. Some of them are as follows:
- min_range - It define minimum value of an integer
- max_range - It defines maximum value of an integer
- FILTER_FLAG_ALLOW_OCTAL - It only allows octal number values
- FILTER_FLAG_ALLOW_HEX - It only allows hexadecimal number values
Example:
<?php
$int = 20;
$min = 11;
$max = 300;
$options=array("options" => array("min_range"=>$min, "max_range"=>$max));
if (filter_var($int, FILTER_VALIDATE_INT, $options) === false) {
echo("Variable value is not within the legal range");
} else {
echo("Variable value is within the legal range");
}
?>
Output of above example is as follows:
Variable value is within the legal range
0 Comment(s)