filter_var_array()

filter_var_array() — Gets multiple variables and optionally filters them.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5 >= 5.2.0, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Filter an associative array of values using FILTER_VALIDATE_* validation filters, FILTER_SANITIZE_* sanitization filters, or custom filters.

Signature

filter_var_array(array $array, array|int $options = FILTER_DEFAULT, bool $add_empty = true): array|false|null

Parameters

ParameterTypeWhat it takes
$arrayarrayAn associative array containing the data to filter.
$optionsarray|intEither an associative array of options, or the filter to apply to each entry, which can either be a validation filter by using one of the FILTER_VALIDATE_* constants, or a sanitization filter by using one of the FILTER_SANITIZE_* constants.
$add_emptyboolAdd missing keys as null to the return value.

Return value

On success, an array containing the values of the requested variables. On failure, false is returned. Missing entries from the input array are added to the returned array as null if add_empty is true, and are omitted entirely if it is false. An entry of the returned array will be false if the filter fails, unless the FILTER_NULL_ON_FAILURE flag is used, in which case it will be null. With the FILTER_FORCE_ARRAY flag, that failure value is wrapped in a one element array like any other result.

Example

A runnable snippet:

$data = [ 'product_id' => 'libgd<script>', 'component' => '10', 'versions' => '2.0.33', 'testscalar' => ['2', '23', '10', '12'], 'testarray' => '2', ]; $filters = [ 'product_id' => FILTER_SANITIZE_ENCODED, 'component' => [ 'filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_FORCE_ARRAY, 'options' => [ 'min_range' => 1, 'max_range' => 10, ], ], 'versions' => [ 'filter' => FILTER_SANITIZE_ENCODED ], 'testscalar' => [ 'filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_REQUIRE_SCALAR, ], 'testarray' => [ 'filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_FORCE_ARRAY, ], 'doesnotexist' => FILTER_VALIDATE_INT, ]; var_dump(filter_var_array($data, $filters));

Output:

array(6) { ["product_id"]=> string(17) "libgd%3Cscript%3E" ["component"]=> array(1) { [0]=> int(10) } ["versions"]=> string(6) "2.0.33" ["testscalar"]=> bool(false) ["testarray"]=> array(1) { [0]=> int(2) } ["doesnotexist"]=> NULL }

See also

filter_input_array(), filter_var(), filter_input()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page filter_var_array() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.