phpvalidation

Best way to check for positive integer (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;
}

Solution

  • 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