Quite possibly one of the most powerful functions that comes bundled with the filter extension is the one called “filter_var_array().” As its name implies, it can be used to apply, in one single round, a specified filter to all of the elements of an array. To demonstrate the actual functionality of this function, I’m going to code a basic example that will use the FILTER_VALIDATE_INT filter that you saw in the previous section. Nonetheless, it’s valid to clarify that all the filters available with the extension can be used with the function in question, so you can imagine how useful it can be for checking multiple values. But it’s time to move past the theory and see how the function can be used to validate whether the elements of a given array are integers. The code sample below does that in a simple manner. Look at it: <?php
// example on using the filter_var_array() function with FILTER_VALIDATE_INT filter $values = array(1, '0.675', -123456, 'This is a string', "abcdef", array(1, 2, 3)); // create an array of filtered values $filtered_values = filter_var_array($values, FILTER_VALIDATE_INT); foreach($filtered_values as $key=>$value) { echo '<p>' . $key .' ---- ' . $value . '</p>'; }
/* displays the following 0 ---- 1
1 ----
2 ---- -123456
3 ----
4 ----
5 ---- Array */ ?> Here you have it. As I mentioned before, the “filter_var_array()” function allows you to apply a specific filter to all of the elements of an array. In this particular case, I decided to use this function with the FILTER_VALIDATE_INT filter, but you may want to try using others and see how well it works. Now, returning to the above example, you can see that the function also returns an array of mixed values, depending on the type of filter applied to the incoming data. Since in this particular case, I’m checking only for integers, the function displays nothing when this condition isn’t satisfied. So far, so good. At this point I’m sure that you’ve already realized the potential of using the “filter_var_array()” function, meaning that it’s time to explore even more capabilities of the filter extension. The next thing that I’m going to discuss will consist of explaining how to utilize the FILTER_VALIDATE_INT filter, this time for validating both octal and hexadecimal integers. Thus, if you wish to learn how this will be accomplished, click on the link below and read the next few lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|