I need to check for a form input value to be a positive integer (not just an integer), and I noticed another snippet using the code below:
$i = $user_input_value; if (!is_numeric($i) || $i < 1 || $i != round($i)) { return TRUE; }
I was wondering if there's any advantage to using the three checks above, instead of just doing something like so:
$i = $user_input_value; if (!is_int($i) && $i < 1) { return TRUE; }
If the Integer is greater than zero then it is a positive integer. If the number is less than zero then it is a negative integer. If the number is equal to zero then it is neither negative nor positive.
The is_int() function checks whether a variable is of type integer or not. This function returns true (1) if the variable is of type integer, otherwise it returns false.
php function CheckNumber($x) { if ($x >= 0) { if ($x > 0) $message = "Positive number"; else $message = "Zero"; } else $message = "Negative number"; echo $message. "\n"; } CheckNumber(5.5); CheckNumber(-10.8); ?>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With