Best way to check for positive integer (PHP)?

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.

Leave a Comment