Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check for positive integer (PHP)?

Tags:

validation

php

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; } 
like image 541
geerlingguy Avatar asked Jan 30 '11 19:01

geerlingguy


People also ask

How do you check if a number is a positive integer?

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.

How do you check if something is an integer in PHP?

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.

How do you find positive and negative numbers in PHP?

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); ?>


1 Answers

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.

like image 98
Jeff Vdovjak Avatar answered Oct 08 '22 19:10

Jeff Vdovjak