Skip to content

filter_var_array()

Introduction

PHP provides a range of built-in functions for filtering and validating user input data. One such function is filter_var_array(), which is used to apply filters to multiple variables at once. In this article, we will provide you with a detailed guide on how to use filter_var_array() in PHP, its syntax, and its benefits.

Syntax

The syntax for filter_var_array() is as follows:

The PHP syntax of filter_var_array()

php
filter_var_array ( array $data , mixed $definition [, bool $add_empty = true ] ) : mixed

The function takes three parameters: the array of input data to be filtered, the definition of the filters to apply, and an optional boolean flag to indicate whether empty input values should be added to the returned array. The function returns the filtered array on success, or false on failure.

Usage

The filter_var_array() function is used to apply validation and sanitization rules to multiple variables at once, such as data submitted via a form. For example, the following code demonstrates how to process form input:

Example of PHP filter_var_array()

php
<?php

$filters = [
    'name' => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
    'age' => FILTER_VALIDATE_INT,
    'email' => FILTER_VALIDATE_EMAIL
];

$data = [
    'name' => $_POST['name'],
    'age' => $_POST['age'],
    'email' => $_POST['email']
];

// $add_empty = false prevents keys with null/empty values from being added to the result
$result = filter_var_array($data, $filters, false);

if ($result === false) {
    // Handle error
}

In this example, the $filters array defines the rules to apply to the input data, and the $data array holds the form values. The filter_var_array() function applies these rules and stores the result in $result.

Note: FILTER_SANITIZE_STRING was removed in PHP 8.0. Use FILTER_SANITIZE_FULL_SPECIAL_CHARS instead. Always check if the function returns false to handle potential failures.

Benefits

Applying filter_var_array() can enhance the security and reliability of your PHP application by processing multiple variables simultaneously. Validating input before further processing ensures your application only accepts expected data, reducing the risk of security vulnerabilities. Additionally, leveraging built-in filter functions improves code quality by keeping validation logic separate from business logic, making your scripts more modular and easier to maintain.

Conclusion

In conclusion, filter_var_array() is a valuable tool for efficiently processing multiple variables in PHP. When combined with other filter functions, it helps maintain secure, high-quality, and readable code.

Practice

What is the purpose of the 'filter_var_array()' function in PHP?

Dual-run preview — compare with live Symfony routes.