CakeFest 2024: The Official CakePHP Conference

filter_var_array

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

filter_var_arrayRetorna múltiple variables y opcionalmente las filtra

Descripción

filter_var_array(array $data, mixed $definition = ?, bool $add_empty = true): mixed

Esta función es útil para recuperar muchos valores sin llamar repetidamente a filter_var().

Parámetros

data

Un array asociativo de claves en formato strings que contiene los datos a filtrar.

definition

Un array definiendo los argumentos. Una clave válida será aquella que contiene un string con el nombre de una variable y un valor válido aquel que o bien es un tipo filter type o un array especificando opcionalmente el filtro, flags y opciones. Si el valor es un array, las claves válidas serán: filter que especifica el tipo filter type, flags que define cualquier flag que deba aplicarse a los filtros, y options que establece cualquier opción que se deba aplicar al filtro. Para entender mejor su funcionamiento, vea el ejemplo inferior.

Este parámetro puede ser tambien un integer indicando una constante de filtro.. Entonces, todos los valores en el array de entrada son filtrados por este filtro.

add_empty

Añade claves faltantes como null al valor devuelto.

Valores devueltos

En caso de éxito un array que contiene los valores de las variables que se han pedido o false en caso de fallo. El valor del array será false si el filtro falla o null si la variable no está definida.

Ejemplos

Ejemplo #1 Ejemplo de filter_var_array()

<?php
error_reporting
(E_ALL | E_STRICT);
$data = array(
'id_producto' => 'libgd<script>',
'componente' => '10',
'versiones' => '2.0.33',
'test_escalar' => array('2', '23', '10', '12'),
'test_array' => '2',
);

$args = array(
'id_producto' => FILTER_SANITIZE_ENCODED,
'componente' => array('filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_FORCE_ARRAY,
'options' => array('min_range' => 1, 'max_range' => 10)
),
'versiones' => FILTER_SANITIZE_ENCODED,
'no_existe' => FILTER_VALIDATE_INT,
'test_scalar' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_REQUIRE_SCALAR,
),
'test_array' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_FORCE_ARRAY,
)

);

$myinputs = filter_var_array($data, $args);

var_dump($myinputs);
echo
"\n";
?>

El resultado del ejemplo sería:

array(6) {
  ["id_producto"]=>
  string(17) "libgd%3Cscript%3E"
  ["componente"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versiones"]=>
  string(6) "2.0.33"
  ["no_existe"]=>
  NULL
  ["test_escalar"]=>
  bool(false)
  ["test_array"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

Historial de cambios

Versión Descripción
5.4.0 Se añadió el parámetro add_empty.

Ver también

add a note

User Contributed Notes 5 notes

up
4
Anonymous
1 year ago
To apply the same filter to many params/keys, use array_fill_keys().

<?php
$data
= array(
'product_id' => 'libgd<script>',
'component' => ' 10 ',
'versions' => '2.0.33',
'testscalar' => array('2', '23', '10', '12'),
'testarray' => '2',
);
$keys = array(
'product_id',
'component',
'versions',
'doesnotexist',
'testscalar',
'testarray'
);
$options = array(
'filter' => FILTER_CALLBACK,
'options' => function ($value) {
return
trim(strip_tags($value));
},
);
$args = array_fill_keys($keys, $options);
/* Result
$args = array(
'product_id' => array(
'filter' => FILTER_CALLBACK,
'options' => function ($value) {
return trim(strip_tags($value));
},
),
'component' => array(
'filter' => FILTER_CALLBACK,
'options' => function ($value) {
return trim(strip_tags($value));
},
),
'versions' => array(
'filter' => FILTER_CALLBACK,
'options' => function ($value) {
return trim(strip_tags($value));
},
),
'doesnotexist' => array(
'filter' => FILTER_CALLBACK,
'options' => function ($value) {
return trim(strip_tags($value));
},
),
'testscalar' => array(
'filter' => FILTER_CALLBACK,
'options' => function ($value) {
return trim(strip_tags($value));
},
),
'testarray' => array(
'filter' => FILTER_CALLBACK,
'options' => function ($value) {
return trim(strip_tags($value));
},
),
);
*/

$myinputs = filter_var_array($data, $args);
var_dump($myinputs);

Output:

array(
6) {
'product_id' =>
string(5) "libgd"
'component'
=>
string(2) "10"
'versions'
=>
string(6) "2.0.33"
'doesnotexist'
=>
NULL
'testscalar' =>
array(
4) {
[
0] =>
string(1) "2"
[1] =>
string(2) "23"
[2] =>
string(2) "10"
[3] =>
string(2) "12"
}
'testarray' =>
string(1) "2"
}
up
8
eguvenc at gmail dot com
14 years ago
<?php
//an example of simply sanitize an array..

$data = array(
'<b>bold</b>',
'<script>javascript</script>',
'P*}i@893746%%%p*.i.*}}|.dw<?php echo "echo works!!";?>');

$myinputs = filter_var_array($data,FILTER_SANITIZE_STRING);

var_dump($myinputs);

//OUTPUT:
//formarray(3) { [0]=> string(4) "bold" [1]=> string(10) "javascript" [2]=> string(26) "P*}i@893746%%%p*.i.*}}|.dw" }
?>
up
1
Vee W.
4 years ago
$emails = [
'a' => 'email1@domain.com',
'b' => '<email2>@domain.com',
];

$result = filter_var_array($emails, FILTER_SANITIZE_EMAIL);
print_r($result);

// the result will be...
// array('a' => 'email1@domain.com', 'b' => 'email2@domain.com')
up
-1
tongcheong77 at gmail dot com
6 years ago
for those who would like to know how to use regular expressions with filter var array. taken from w3 schools.

$data = array(

'regxp' => 'michael'

);

$args = array(

'regxp' => array(

'filter'=>FILTER_VALIDATE_REGEXP | FILTER_SANITIZE_STRING,
'options'=>array('regexp'=>"/^michael$/"),

));

$output=filter_var_array($data,$args);

var_dump($output); // array(1) { ["regxp"]=> string(7) "michael" }

- bruce tong
up
-2
tongcheong77 at gmail dot com
6 years ago
an update to previous post.

using regular expressions along with another filter in filter var array

$data = array(

'regxp' => "`\tcafé\n`"

);

$args = array(

'regxp' => array(

'filter'=>FILTER_VALIDATE_REGEXP | FILTER_SANITIZE_STRING,
'flags'=>FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_BACKTICK,
'options'=>array('regexp'=>"/t(.*)/"),

));

$output=filter_var_array($data,$args);

var_dump($output); // array(1) { ["regxp"]=> string(3) "caf" }

-bruce tong
To Top