PHP Filters Advanced
In this page:
Filtering an Entire Array with filter_var_array()
filter_var_array($data, $rules) applies a different filter to every key in an array in one call, following a $rules array that maps each key name to the filter it should use -- much more convenient than calling filter_var() separately for every single form field.
Note: Define your filter rules array once, close to where the form fields are declared, so validation rules stay easy to find and update alongside the fields they apply to.
Warning: A key present in $data but missing from the $rules array is passed through completely unfiltered by default -- explicitly include every key you want validated.
Example: Filtering an Entire Array with filter_var_array()
<?php
$data = ["email" => "[email protected]", "age" => "25"];
$rules = ["email" => FILTER_VALIDATE_EMAIL, "age" => FILTER_VALIDATE_INT];
print_r(filter_var_array($data, $rules));
?>
Login to try C/C++/Java/PHP code in the editor
Writing a Custom Filter with FILTER_CALLBACK
FILTER_CALLBACK lets you supply your own function as the validation rule, for checks PHP's built-in filters do not directly support -- like confirming a username only contains letters, numbers, and underscores, or that a value matches a business-specific rule.
Note: Have your callback function return false explicitly for invalid input, matching the same success/failure convention every built-in filter follows.
Warning: A FILTER_CALLBACK function that forgets to return anything on the invalid path implicitly returns null, which can be mistaken for a passing result if not checked carefully.
Example: Writing a Custom Filter with FILTER_CALLBACK
<?php
$username = "alice_99";
$options = ["options" => function ($value) {
return preg_match('/^\w+$/', $value) ? $value : false;
}];
var_dump(filter_var($username, FILTER_CALLBACK, $options));
?>
Login to try C/C++/Java/PHP code in the editor
Fine-Tuning Filters with Flags
Many filters accept additional flags to adjust their exact behavior -- FILTER_FLAG_ALLOW_THOUSAND lets FILTER_VALIDATE_INT accept thousands separators, and FILTER_NULL_ON_FAILURE changes a boolean filter to return null (instead of false) specifically for unrecognized input, distinguishing it from a genuine "false" value.
Note: Check the PHP manual's filter flag list for the specific filter you are using -- many filters support multiple flags that can be combined with the bitwise OR operator.
Warning: Combining incompatible flags for a given filter type has no defined effect and can behave inconsistently -- only combine flags documented as compatible together.
Example: Fine-Tuning Filters with Flags
<?php
var_dump(filter_var("1,000", FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_THOUSAND));
var_dump(filter_var("maybe", FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
?>
Login to try C/C++/Java/PHP code in the editor
Sanitizing Multiple Fields at Once
filter_var_array() works for sanitization filters too, not just validation ones -- applying FILTER_SANITIZE_STRING-style cleanup or FILTER_SANITIZE_NUMBER_INT across an entire array of submitted fields in one call, cleaning up several inputs simultaneously.
Note: Sanitize first, then validate, when a field genuinely needs both steps -- sanitizing removes unwanted characters, while validation confirms the cleaned value is actually correct.
Warning: Sanitization filters strip or encode characters rather than rejecting invalid input outright -- they do not replace validation, since sanitized-but-still-wrong data can still pass through.
Example: Sanitizing Multiple Fields at Once
<?php
$data = ["age" => "25abc", "phone" => "555-1234"];
$rules = ["age" => FILTER_SANITIZE_NUMBER_INT, "phone" => FILTER_SANITIZE_NUMBER_INT];
print_r(filter_var_array($data, $rules));
?>
Login to try C/C++/Java/PHP code in the editor
Filtering Superglobal Input Directly
filter_input(INPUT_GET, "key", $filter) or filter_input(INPUT_POST, "key", $filter) reads and filters a value directly from the $_GET or $_POST superglobals in one step, without touching the raw superglobal array at all -- a slightly safer, more explicit pattern than reading and then separately filtering.
Note: filter_input() returns null if the requested key was not present at all, distinct from false, which means the key existed but failed the filter -- check for both cases separately.
Warning: filter_input() reads directly from PHP's internal request data at the time it was first parsed -- it will not reflect changes your own script makes to $_GET or $_POST afterward.
Example: Filtering Superglobal Input Directly
<?php
$_GET['id'] = "42";
$id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
var_dump($id);
?>
Login to try C/C++/Java/PHP code in the editor
- Forgetting that filter_var() returns false on failure for most filters, which is itself a valid boolean value -- always compare with === false rather than a loose truthy check.
- Not realizing FILTER_VALIDATE_INT and similar filters reject values with leading/trailing whitespace by default unless the appropriate flag is added.
- Writing a custom FILTER_CALLBACK function that does not itself return false on invalid input, breaking the consistent success/failure contract other filters follow.
- filter_var_array() applies filters to every value in an array at once, following a rules array that maps keys to filter definitions.
- FILTER_CALLBACK lets you supply your own custom validation function for rules PHP's built-in filters do not cover.
- Filter flags like FILTER_FLAG_ALLOW_THOUSAND or FILTER_NULL_ON_FAILURE fine-tune exactly how a filter behaves.
The full PHP filter extension, including filter_var_array() and FILTER_CALLBACK, has been available since PHP 5.2.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: