filter_var_array

Filters many values in an array at once against a per-key set of validation or sanitization rules.

Signature
filter_var_array(array $array, array|int $options = FILTER_DEFAULT, bool $add_empty = true): array|false|null
  • Added in PHP 5.2.0

Parameters

ParameterTypeDescription
$arrayarrayAn associative array containing the data to filter.
$optionsoptionalarray|int= FILTER_DEFAULTEither a single filter constant applied to every entry, or an array mapping each key to a filter constant or to an array with 'filter', 'flags' and 'options' keys.
$add_emptyoptionalbool= trueWhen true, keys named in options but missing from the input array are added to the result as null; when false they are omitted.

Return value

array|false|nullAn array of filtered values on success, or false on failure. Entries whose filter fails are false, and keys named in options but missing from the input are null when add_empty is true.

Errors

Throws a ValueError when incompatible flags are combined, such as FILTER_NULL_ON_FAILURE together with FILTER_THROW_ON_FAILURE. An unknown filter ID does not throw: given per key (['a' => ['filter' => 99999]]) the value is returned unfiltered, and passed as the whole options argument it raises an "Unknown filter with ID %d" warning and returns false. In PHP 8.5, a validation failure throws Filter\FilterFailedException when FILTER_THROW_ON_FAILURE is set.

Changelog

  • PHP 8.5The FILTER_THROW_ON_FAILURE flag was added; a failing validation filter throws Filter\FilterFailedException instead of yielding false. It cannot be combined with FILTER_NULL_ON_FAILURE.
  • PHP 8.1FILTER_SANITIZE_STRING and its alias FILTER_SANITIZE_STRIPPED are deprecated; use htmlspecialchars() instead.
  • PHP 8.0FILTER_VALIDATE_BOOL was introduced as the canonical name for FILTER_VALIDATE_BOOLEAN.

filter_var_array() applies a whole set of rules to an array in one call. You give it the data and a second array whose keys line up with the data's keys, and you get back an array of validated, correctly typed values.

When to reach for it

This is the one to use for data you already hold: a decoded JSON body, a row from a CSV import, a config array, a queue message, an array you assembled in a test. Unlike filter_input_array() it does not care about the SAPI, so it works identically on the CLI and under PHPUnit.

The rule array doubles as a whitelist and as documentation of the payload's shape. Keys in the input that are not named in the rules are dropped, so nothing unexpected survives into your domain code.

What trips people up

Failures are values, not exceptions. A field that fails its filter becomes false inside the returned array, sitting quietly alongside the good data. Loop with === comparisons, or in PHP 8.5 pass FILTER_THROW_ON_FAILURE so a bad field stops the request.

A key present in the data but not in the rules is discarded, and a key in the rules but not in the data becomes null unless you pass false for add_empty.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Validate a decoded JSON request body in an API controller without touching the superglobals.
  • Clean and type-check each row of a CSV import before inserting it.
  • Validate an array of settings loaded from a config file at boot, failing fast on a bad value.
  • Run the same validation rules in a unit test, where filter_input_array would return null.

Frequently asked questions

What is the difference between filter_var_array and filter_input_array?

filter_var_array filters an array you supply, while filter_input_array reads the raw request data for an INPUT_* type. Use filter_var_array for decoded JSON, config arrays and anything you want to unit test, since filter_input_array returns null on the CLI.

Does filter_var_array keep keys that are not in the filter definition?

No. Only keys named in the options array appear in the result, which makes the rule array an implicit whitelist. Pass a single filter constant instead of an array if you want every input key filtered and kept.

How do I know which entry failed?

Compare each returned entry with === false; that is the failure marker. Keys named in the rules but missing from the input are null instead, unless you pass false for add_empty.

More examples

One filter for every entry

Passing a single constant applies it to every key. <code>' 10 '</code> validates to <code>int(10)</code> because surrounding whitespace is allowed, <code>'0'</code> validates to <code>int(0)</code>, and only <code>'x'</code> comes back as <code>bool(false)</code>. The loop shows why <code>=== false</code> matters: a truthiness test would wrongly flag the valid 0.

Example · php
<?php
$data = ['a' => ' 10 ', 'b' => 'x', 'c' => '3', 'd' => '0'];

var_dump(filter_var_array($data, FILTER_VALIDATE_INT));

// Spot the failures explicitly:
foreach (filter_var_array($data, FILTER_VALIDATE_INT) as $k => $v) {
    echo $k, ': ', $v === false ? 'INVALID' : $v, "\n";
}

Array fields, forced arrays and dropped keys

<code>FILTER_REQUIRE_ARRAY</code> filters each element of <code>tags</code> individually, and <code>FILTER_FORCE_ARRAY</code> wraps the scalar <code>id</code> so it comes back as <code>[7]</code> — useful when a field may legitimately be single or multi-valued. Passing <code>false</code> for add_empty removes the unsupplied <code>note</code> key instead of setting it to null.

Example · php
<?php
$data = ['tags' => ['php', '<b>web</b>'], 'id' => '7'];

$filters = [
    'tags' => ['filter' => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
               'flags'  => FILTER_REQUIRE_ARRAY],
    'id'   => ['filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_FORCE_ARRAY],
    'note' => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
];

print_r(filter_var_array($data, $filters, false));

Validating a decoded JSON payload

The string <code>"3"</code> is returned as <code>int(3)</code> and <code>"yes"</code> as <code>bool(true)</code>, so the array handed to your domain code is properly typed. FILTER_NULL_ON_FAILURE on the boolean field means a garbage value becomes null rather than an indistinguishable false.

Example · php
<?php
$body = json_decode('{"email":"[email protected]","qty":"3","gift":"yes"}', true);

$rules = [
    'email' => FILTER_VALIDATE_EMAIL,
    'qty'   => ['filter' => FILTER_VALIDATE_INT, 'options' => ['min_range' => 1]],
    'gift'  => ['filter' => FILTER_VALIDATE_BOOL, 'flags' => FILTER_NULL_ON_FAILURE],
];

$clean = filter_var_array($body, $rules);
var_dump($clean['qty'], $clean['gift']);

Discussion

  • Be the first to comment on this lesson.