Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php filter_var fails with zero on FILTER_VALIDATE_INT

Tags:

php

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?

like image 507
sapatos Avatar asked Mar 24 '14 07:03

sapatos


2 Answers

People should test false instead:

if (filter_var($value, FILTER_VALIDATE_INT) === false) {
    // $value is not an integer
}
like image 112
datasn.io Avatar answered Oct 21 '22 13:10

datasn.io


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.

like image 37
xdazz Avatar answered Oct 21 '22 12:10

xdazz