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?

3
  • 5
    'false' is not a boolean, it's a string.
    – BoltClock
    Feb 2, 2012 at 15:52
  • 'false' should be just false in this case otherwise it will be treated as a string.
    – Treffynnon
    Feb 2, 2012 at 16:05
  • it still returns the error message with false...
    – Run
    Feb 2, 2012 at 16:14

1 Answer 1

24

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'"
1
  • 1
    The conclusion was wrong though. You do need === NULL to check for the incorrect input.
    – mario
    Feb 2, 2012 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.