Search code examples
phparraysfiltersanitization

PHP: Apply a common filter with filter_var_array?


I've tried various combinations and permutations of filter_var_array() and have yet to find the answer to this:

Given a rather large associative array, I need to apply FILTER_SANITIZE_STRING with the FILTER_FLAG_STRIP_LOW flag to ALL of the elements in the array.

So:

filter_var_array($my_big_array,FILTER_SANITIZE_STRING);

applies the FILTER_SANITIZE_STRING filter but without the FILTER_FLAG_STRIP_LOW flag.

And...

filter_var_array($my_big_array,FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);

Brings up an error.

Is it possible to easily apply a common filter using filter_var_array()?


Solution

  • Good filter_var_array() syntax

    The second filter_var_array() argument needs to be a proper $definition as per the PHP manual.

    Example:

    Just make sure you do not put the flags inside their own array. Options can be in an array, but the flags need to be seen as one whole thing separated by pipes.

       $def = [
                 'firstName' => ['filter' => FILTER_SANITIZE_STRING,
                                 'flags'  => FILTER_REQUIRE_SCALAR | FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH],
                 'lastName'  => ['filter' => FILTER_SANITIZE_STRING,
                                 'flags'  => FILTER_REQUIRE_SCALAR | FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH]
              ];