Best way to check for positive integer (PHP)?

The best way for checking for positive integers when the variable can be INTEGER or STRING representing the integer:

 if ((is_int($value) || ctype_digit($value)) && (int)$value > 0 ) { // int }

is_int() will return true if the value type is integer. ctype_digit() will return true if the type is string but the value of the string is an integer.

The difference between this check and is_numeric() is that is_numeric() will return true even for the values that represent numbers that are not integers (e.g. "+0.123").


Not sure why there's no suggestion to use filter_var on this. I know it's an old thread, but maybe it will help someone out (after all, I ended up here, right?).

$filter_options = array( 
    'options' => array( 'min_range' => 0) 
);


if( filter_var( $i, FILTER_VALIDATE_INT, $filter_options ) !== FALSE) {
   ...
}

You could also add a maximum value as well.

$filter_options = array(
    'options' => array( 'min_range' => 0,
                        'max_range' => 100 )
);

Learn more about filters.


the difference between your two code snippets is that is_numeric($i) also returns true if $i is a numeric string, but is_int($i) only returns true if $i is an integer and not if $i is an integer string. That is why you should use the first code snippet if you also want to return true if $i is an integer string (e.g. if $i == "19" and not $i == 19).

See these references for more information:

php is_numeric function

php is_int function

Tags:

Php

Validation