Fortunately, the filter extension comes packaged with a helpful function called “filter_var().”As its name suggests, it applies a specified filter to a given PHP variable. So, since the first step of my plan consists of demonstrating how to check if a value is an integer, I’m going to use the function to perform this task. Now, look at the following code snippet, which makes use of a new filter named FILTER_VALIDATE_INT that checks for integers: // example on using the FILTER_VALIDATE_INT filter
$input = '123456'; // check to see if $input is an integer echo filter_var($input, FILTER_VALIDATE_INT); // displays 123456 As shown above, the “filter_var()” function initially accepts two arguments. The first one is the value that will be filtered and the second one is the filter that will be applied to it. In this introductory example I wish to check if the value of the $input variable is actually an integer, so I use the FILTER_VALIDATE_INT filter. Also, you should notice that the above example will echo the value 123456 on screen, even when the value passed in to be filtered is in reality a string. This means that the filter doesn’t care if the value is numeric or literal, as long as it contains integers. To demonstrate this concept more clearly, here’s another example that uses the FILTER_VALIDATE_INT filter to check a true integer value: $input = 123456; // check to see if $input is an integer echo filter_var($input, FILTER_VALIDATE_INT); // displays 123456 That example was pretty simple to understand, wasn’t it? Now, look at the following one, which passes a float number to the filter: $input = 1.2; // check to see if $input is an integer echo filter_var($input, FILTER_VALIDATE_INT); // displays nothing In this case, the “filter_var()” function will return FALSE and nothing will be displayed on screen, since the value passed to it is a float number. In addition, here are a couple of more readable examples that hopefully will help you grasp more quickly how the FILTER_VALIDATE_INT filter works: $input = '4.56'; if(filter_var($input, FILTER_VALIDATE_INT) === FALSE) // displays Input is not an integer. { echo 'Input is not an integer.'; } else { echo 'Input is an integer.'; }
$input = '123456'; if(filter_var($input, FILTER_VALIDATE_INT) === FALSE) // displays Input is an integer. { echo 'Input is not an integer.'; } else { echo 'Input is an integer.'; } As you can see in the couple of examples above, the FILTER_VALIDATE_INT filter checks if a given value is an integer or not, when used in conjunction with the “filter_var()” function. However, the filter not only permits you to validate an integer, but determine if it’s within a specified range. This additional functionality provided by the filter will be discussed in the last segment of this tutorial. So please read the following section.
blog comments powered by Disqus |
|
|
|
|
|
|
|