The filter_var_array() function in PHP allows you to validate and sanitize multiple variables at once. It is commonly used for processing form data efficiently using predefined rules.
The function applies filters defined in one array to corresponding values in another array.
// Syntax definition of filter_var_array
filter_var_array(array $data, array $filters, int $flags = 0, int $options = 0);
// Sample form data
$data = [
'email' => 'test@example.com',
'url' => 'https://www.example.com',
'age' => '25',
'name' => '<h1>John Doe</h1>',
];
// Filters for each input
$filters = [
'email' => FILTER_VALIDATE_EMAIL,
'url' => FILTER_VALIDATE_URL,
'age' => FILTER_VALIDATE_INT,
'name' => FILTER_SANITIZE_STRING,
];
// Apply filters
$result = filter_var_array($data, $filters);
// Display filtered output
print_r($result);
Valid values are returned as-is, invalid values return NULL, and sanitized values have unsafe characters removed.
Imagine submitting a form with email, URL, age, and name fields. PHP processes them together and instantly validates each input based on predefined rules.