php-src icon indicating copy to clipboard operation
php-src copied to clipboard

filter_var("false", FILTER_VALIDATE_BOOL returns the set default value

Open TobiGr opened this issue 4 years ago • 6 comments

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

TobiGr avatar Jan 06 '22 10:01 TobiGr

false/false is the current behavior. https://3v4l.org/mKvrT

damianwadley avatar Jan 06 '22 10:01 damianwadley

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.

TobiGr avatar Jan 06 '22 10:01 TobiGr

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.

damianwadley avatar Jan 06 '22 10:01 damianwadley

Closing per @damianwadley's comment above. At this point in time, "fixing" this would likely cause more harm than good.

cmb69 avatar Jan 06 '22 11:01 cmb69

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_FAILURE is set, false is returned only for "0", "false", "off", "no", and "", and null is returned for all non-boolean values.

TobiGr avatar Jan 11 '22 08:01 TobiGr

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.

damianwadley avatar Jan 11 '22 09:01 damianwadley