Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

filter_var_array()

Filter an existing array using rules keyed by field name.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

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

Filter an existing array using rules keyed by field name. Under the normal flags a failed validation produces false in that field. A missing requested field becomes null with add_empty=true and is omitted with false. Fields absent from the rule map are omitted. FILTER_REQUIRE_ARRAY filters each element of an array field. Combining it with FILTER_NULL_ON_FAILURE marks invalid elements as null.

Signature

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

Example output

[{"qty":3,"level":false,"memo":null},{"qty":3,"level":false}]
{"scores":[3,null]}

Examples

<?php
$data=["qty"=>"3","level"=>"x","extra"=>7]; $rules=["qty"=>FILTER_VALIDATE_INT,"level"=>FILTER_VALIDATE_INT,"memo"=>FILTER_DEFAULT];
echo json_encode([filter_var_array($data,$rules),filter_var_array($data,$rules,false)]);
$rule=["scores"=>["filter"=>FILTER_VALIDATE_INT,"flags"=>FILTER_REQUIRE_ARRAY | FILTER_NULL_ON_FAILURE]];
echo "\n",json_encode(filter_var_array(["scores"=>["3","x"]],$rule));

Result

[{"qty":3,"level":false,"memo":null},{"qty":3,"level":false}]
{"scores":[3,null]}

Sources