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.
Thanks for sharing… I thought I was doing something wrong!!!
😉
Thank you!!!
Thanks a lot from Kherson.
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.
It’s amazing in favor of me to have a site, which is useful in support of my know-how. thanks admin
Hello. Thank for this. God willing to stay healthy