Home » Php » php filter_var fails with zero on FILTER_VALIDATE_INT

php filter_var fails with zero on FILTER_VALIDATE_INT

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m confused the following throws an exception:

if (!filter_var(0, FILTER_VALIDATE_INT))
    throw new Exception("Non numeric field passed " . $field . " when expecting a number: " . $variable . " passed instead");

anything positive works fine? I’ve tried intval(0) and still nothing. is zero not an integer?

How to&Answers:

People should test false instead:

if (filter_var($value, FILTER_VALIDATE_INT) === false) {
    // $value is not an integer
}

Answer:

filter_var Returns the filtered data, or FALSE if the filter fails.

filter_var(0, FILTER_VALIDATE_INT) returns int(0), and is a falsy value, !filter_var(0, FILTER_VALIDATE_INT) will be true.