filter_var("false", FILTER_VALIDATE_BOOL returns the set default value
Description
The following code:
<?php
var_dump(filter_var("false", FILTER_VALIDATE_BOOLEAN, ['options' => ['default' => 2]]));
var_dump(filter_var("false", FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
Resulted in this output:
int(2)
bool(false)
But I expected this output instead:
bool(false)
bool(false)
Might be related: https://bugs.php.net/bug.php?id=49510
PHP Version
7.4.27
Operating System
Debian 4.19.208-1
false/false is the current behavior. https://3v4l.org/mKvrT
My bad, I had a typo in the example code. I added a white space in the name of the default key. Fixed the typo now and the behaviour is there as described in the original post.
Oh, I didn't notice that either.
Technically this behavior is correct: without FILTER_NULL_ON_FAILURE, the filter only "allows" truthy values, and since "false" is not truthy it's rejected - and the default is used. That flag adds an additional behavior to give special handling to falsey values, so no flag means no special handling.
It might be a bit surprising, but (a) it's documented like this, (b) there is a "workaround" of providing FILTER_NULL_ON_FAILURE, and (c) changing this could break compatibility.
Closing per @damianwadley's comment above. At this point in time, "fixing" this would likely cause more harm than good.
I am sorry to bother you again, but I looked deeper into the issue and still got return values which I do not expect.
var_dump(filter_var(null, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
var_dump(filter_var(null, FILTER_VALIDATE_BOOLEAN, ['options' => ['default' => 2], 'flags' => FILTER_NULL_ON_FAILURE]));
results in
bool(false)
bool(false)
although the docs say
If
FILTER_NULL_ON_FAILUREis set,falseis returned only for "0", "false", "off", "no", and "", andnullis returned for all non-boolean values.
The docs also say
value
Value to filter. Note that scalar values are converted to string internally before they are filtered.
and null converted to a string is an empty string.