Since you learned in the previous segment how to use the FILTER_VALIDATE_INT filter to validate integers, I’m now going to explain another way to use it. This time we'll check not only if a given value is an integer, but if it’s within a specified range. How can this be done? It’s simple, really; adding an optional array to the “filter_var()” function allows you to specify minimal and maximal boundaries for a determined value. The following code samples show in a nutshell how to accomplish this task in a truly intuitive way. Take a look at them:
$min = 1; $max = 99; $input = 101; if(filter_var($input, FILTER_VALIDATE_INT, array("options" => array("min_range" => $min, "max_range"=> $max ))) === FALSE) // displays Error: Input must be a value between 1 and 99 (Correct specification for the min and max options) { echo 'Error: Input must be a value between 1 and 99.'; } else { echo 'Input is correct'; }
$min = 1; $max = 99; $input = 101; if(filter_var($input, FILTER_VALIDATE_INT, array("options" => array("max_range"=> $max ))) === FALSE) // displays Error: Input must be a value between 1 and 99 (Specifies only the max option) { echo 'Error: Input must be a value between 1 and 99.'; } else { echo 'Input is correct'; } As I said before, by adding an “options” array to the “filter_var()” function it’s possible to check not only if the inputted value is an integer, but if it belongs to a specified range. In the first case, both minimal and maximal boundaries have been specified, while in the second example, only the upper limit has been set. From the previous code samples, it’s easy to see how useful the FILTER_VALIDATE_INT filter can be for validating integers. However, I’m only scratching the surface of the PHP 5 filter library; as you saw at the beginning, it comes packaged with many other handy filters. These will be discussed in successive articles of this series. Final thoughts In this initial chapter of the series, I introduced you to using the filter extension that comes included with PHP 5. As you were able to see in all of the code samples included previously, checking to see whether or not a specified value is an integer is an extremely straightforward process thanks to the help of the FILTER_VALIDATE_INT filter. In the forthcoming article, I’m going to explain how to use the filter extension to validate array elements and to check both octal and hexadecimal integers. Don’t miss the next part!
blog comments powered by Disqus |
|
|
|
|
|
|
|