8

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?

sapatos
  • 1,292
  • 3
  • 21
  • 44

2 Answers2

16

People should test false instead:

if (filter_var($value, FILTER_VALIDATE_INT) === false) {
    // $value is not an integer
}
datasn.io
  • 12,564
  • 28
  • 113
  • 154
9

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.

xdazz
  • 158,678
  • 38
  • 247
  • 274