Search code examples
phpbooleanfilter-var

The input value of false for FILTER_VALIDATE_BOOLEAN


I want the input to accpet 'true' or 'false' only, so I am trying to use FILTER_VALIDATE_BOOLEAN to do that,

if (!filter_var('false', FILTER_VALIDATE_BOOLEAN)) 
{
    $error = true;
    echo 'error';
}

It echoes the error message but it should not.

How can I make it right?


Solution

  • Have a look at the manual http://www.php.net/manual/en/filter.filters.validate.php

    Your syntax/usage is correct. filter_var('false', FILTER_VALIDATE_BOOLEAN) however does not verify the pattern, it converts the input string into the accordingly typed value.

    To make it explicit:

    var_dump(filter_var('false', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
    

    Returns the boolean false
    .

    var_dump(filter_var('true', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
    

    Returns the boolean true
    .

    var_dump(filter_var('wrong', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
    

    Returns NULL.
    That's why I added the second option. The input string does neither classify as true nor false.

    So you actually have to check with === NULL for your condition. That would give you the result you probably desired:

    if (filter_var('false', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === NULL) 
    {
        echo "Input did not evaluate to boolean 'false' nor 'true'"