Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25755

Why does filter_var() do not accept 0 as boolean?

i had to validate a variable which should have boolean value either 1 or 0. i tried using filter_var(), the problem with the function is if it gets 0 as input it will return false, isn't 0 considered to be a boolean? if yes then why is the function returning false?

the following condition is returned true

filter_var(1, FILTER_VALIDATE_BOOLEAN);

whereas if i use 0 as input it will return false

filter_var(0, FILTER_VALIDATE_BOOLEAN);

Upvotes: 1

Views: 1091

Answers (2)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272667

According to http://www.php.net/manual/en/filter.filters.validate.php:

FILTER_VALIDATE_BOOLEAN

Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise.

If you want to distinguish between FALSE as a value, and FALSE indicating failure, then you need to use the FILTER_NULL_ON_FAILURE flag.

Upvotes: 4

N.B.
N.B.

Reputation: 14081

Because zero is boolean false?

Upvotes: 1

Related Questions