filter_var boolean returning false

2.6k Views Asked by At

This is weird

var_dump(filter_var(true, FILTER_VALIDATE_BOOLEAN));
var_dump(filter_var(false, FILTER_VALIDATE_BOOLEAN));

bool(true)
bool(false)

What an I missing here? Surely they should both be true? If not how can I validate a false boolean?

Edit: To clarify. I need to validate a false boolean. To ensure it's not a string, int, float or anything else. e.g.

$var = false; //true
$var = true; //true
$var = 'foo'; //false
$var = 1; //false

Perhaps I asked my question incorrectly or I've evolved it too much ad I should ask another question.

Solution I went for was:

$result = filter_var($bool, FILTER_VALIDATE_BOOLEAN) && ($bool===true||$bool===false);
1

There are 1 best solutions below

3
On BEST ANSWER

From the manual:-

If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.

Set this and if null is returned, you don't have a bool (or boolish) value.

For example:-

var_dump(filter_var(true, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
var_dump(filter_var(false, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
var_dump(filter_var(2, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));

See it working

However, it may be that is_bool() is more appropriate here.