PHP validation booleans using filter_var

RS7 picture RS7 · Feb 3, 2012 · Viewed 7.5k times · Source

I'm using filter_var to validate boolean values but I did not expect it to not recognize FALSE. Why does this happen?

filter_var(FALSE, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)

returns

null

Answer

dkamins picture dkamins · Feb 3, 2012

filter_var is new as of PHP 5.2. You've run into a known bug: https://bugs.php.net/bug.php?id=49510 Feel free to vote on or comment on that bug.

You're trying to do something like this:

$v = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)

There are a number of cheap workarounds like this:

$v = $v===FALSE ? FALSE : filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)