Search code examples
phpfilter-var

Why does filter_var() do not accept 0 as boolean?


i had to validate a variable which should have boolean value either 1 or 0. i tried using filter_var(), the problem with the function is if it gets 0 as input it will return false, isn't 0 considered to be a boolean? if yes then why is the function returning false?

the following condition is returned true

filter_var(1, FILTER_VALIDATE_BOOLEAN);

whereas if i use 0 as input it will return false

filter_var(0, FILTER_VALIDATE_BOOLEAN);

Solution

  • According to http://www.php.net/manual/en/filter.filters.validate.php:

    FILTER_VALIDATE_BOOLEAN

    Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise.

    If you want to distinguish between FALSE as a value, and FALSE indicating failure, then you need to use the FILTER_NULL_ON_FAILURE flag.