FILTER_VALIDATE_INT And 0

Filter_var function in php is a very useful built-in tool for server side form validation, but there is a minor problem when you validate an integer which is zero. It does not accept zero as a valid integer.

If you use following to validate an integer input

 if(isset($inputvariable) && filter_var($inputvariable, FILTER_VALIDATE_INT))
  {
      // valid integer input, except 0
  }

When $inputvariable is zero, if statement is evaluated as false, this is due to filter_var returns the filtered data if validation is successful , and FALSE if filter fails.

In this case, filter_var($inputvariable, FILTER_VALIDATE_INT) returns int(0) not FALSE, but php auto type casts int 0 into FALSE, so whole if statement is false.

The solution does not have to be changing integer filer to regex FILTER_VALIDATE_REGEXP, you still can use the same int filter through the use of ‘===’

 if(isset($inputvariable) &&(filter_var($inputvariable, FILTER_VALIDATE_INT)===0 ||!filter_var($inputvariable, FILTER_VALIDATE_INT)===False ))
{
 // valid integer input including 0
}

Using ‘===’ will avoid automatic type casting in evaluation.

This entry was posted on Thursday, January 6th, 2011 at 8:45 pm and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

6 Responses to “FILTER_VALIDATE_INT And 0”

  1. kanenas.net says:

    Thanks for sharing… I thought I was doing something wrong!!!
    😉

  2. Jorge Flores says:

    Thank you!!!

  3. Michael says:

    Thanks a lot from Kherson.

  4. M says:

    Or just:
    if(isset($inputvariable) && (filter_var($inputvariable, FILTER_VALIDATE_INT)!==False ))
    – no need for the extra ===0 test, since (0!==FALSE) avoids type casting and evaluates to TRUE.

  5. Celina says:

    It’s amazing in favor of me to have a site, which is useful in support of my know-how. thanks admin

  6. para says:

    Hello. Thank for this. God willing to stay healthy

Leave a Reply

*