The input value of false for FILTER_VALIDATE_BOOLEAN
Asked Answered
L

1

7

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?

Lurid answered 2/2, 2012 at 15:51 Comment(3)
'false' is not a boolean, it's a string.Harris
'false' should be just false in this case otherwise it will be treated as a string.Antimacassar
it still returns the error message with false...Lurid
P
23

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'"
Pregnant answered 2/2, 2012 at 16:23 Comment(1)
The conclusion was wrong though. You do need === NULL to check for the incorrect input.Pregnant

© 2022 - 2024 — McMap. All rights reserved.