59

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;
}
3
  • the last check is only to see if the number is a integer. Using this check really depends on your requirements
    – Ass3mbler
    Jan 30, 2011 at 19:22
  • 2
    ...You are checking for a negative number in the code currently. Jan 30, 2011 at 19:26
  • Fixed! Sorry about that. Jan 30, 2011 at 19:36

21 Answers 21

55

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.

4
  • Note that this will still accept numeric strings like '123'. If you want to disallow zeros, set min_range option to 1.
    – BadHorsie
    Apr 10, 2019 at 15:28
  • FILTER_VALIDATE_INT doesn't return false for the string '+5'.
    – Wadih M.
    Apr 27, 2019 at 18:25
  • 0 is not a positive integer, so I would set min_range to 1.
    – Adam
    Oct 8, 2019 at 6:26
  • That's what the lack of type safety has driven the language into. Feb 27, 2023 at 0:38
37

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

2
  • 2
    Just trying that code out, I am finding even that is not enough, since it validates ' 123' as an integer. I needed to add $i !== trim($i) to catch leading spaces. It seems that ' 123' == '123' even when you are sure the two values are strings, but PHP does not treat them as strings when comparing them that way.
    – Jason
    Feb 17, 2013 at 22:05
  • 1
    Notice that query string values (GET parameters) are always passed as string, even if the value if numeric. Sep 29, 2016 at 8:41
28

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").

2
  • 2
    +1 seems by far the cleanest - it also works with super long strings made of digits. (Even when this string starts with -)
    – Dimitry K
    Dec 14, 2015 at 18:07
  • 1
    Note that it treats numerical strings with leading zeros (i.e. '00123') as integers, while FILTER_VALIDATE_INT does not.
    – retrowaver
    Mar 8, 2018 at 19:26
15

It's definitely heading towards the land of micro-optimisation, but hey: the code I'm working on chews through millions of items every day and it's Friday. So I did a little bit of experimenting...

for ($i = 0; $i < 1000000; $i++) {
    // Option 1: simple casting/equivalence testing
    if ((int) $value == $value && $value > 0) { ... }

    // Option 2: using is_int() and ctype_digit().  Note that ctype_digit implicitly rejects negative values!
    if ((is_int($value) && $value > 0) || ctype_digit($value)) { ... }

    // Option 3: regular expressions
    if (preg_match('/^\d+$/', $value)) { ... }
}

I then ran the above tests for both integer and string values

Option 1: simple casting/equivalence testing

  • Integer: 0.3s
  • String: 0.4s

Option 2: using is_int() and ctype_digit()

  • Integer: 0.9s
  • String: 1.45s

Option 3: regular expressions

  • Integer: 1.83s
  • String: 1.60s

Perhaps unsurprisingly, option 1 is by far the quickest, since there's no function calls, just casting. It's also worth noting that unlike the other methods, option 1 treats the string-float-integer value "5.0" as an integer:

$valList = array(5, '5', '5.0', -5, '-5', 'fred');
foreach ($valList as $value) {
    if ((int) $value == $value && $value > 0) {
        print "Yes: " . var_export($value, true) . " is a positive integer\n";
    } else {
        print "No: " . var_export($value, true) . " is not a positive integer\n";
    }
}

Yes: 5 is a positive integer
Yes: '5' is a positive integer
Yes: '5.0' is a positive integer
No: -5 is not a positive integer
No: '-5' is not a positive integer
No: 'fred' is not a positive integer

Whether or not that's a good thing for your particular use-case is left as an exercise for the reader...

5

The other best way to check a Integer number is using regular expression. You can use the following code to check Integer value. It will false for float values.

if(preg_match('/^\d+$/',$i)) {
  // valid input.
} else {
  // invalid input.
}

It's better if you can check whether $i > 0 too.

1
  • this will return TRUE also for 0. Nov 12, 2015 at 12:37
3
    preg_match('{^[0-9]*$}',$string))

and if you want to limit the length:

    preg_match('{^[0-9]{1,3}$}',$string)) //minimum of 1 max of 3

So pisitive int with a max length of 6:

    if(preg_match('{^[0-9]{1,6}$}',$string)) && $string >= 0)
2
  • does the preg_match allow negative int?
    – SuperSpy
    Jan 30, 2011 at 19:28
  • Another interesting approach... but this is harder to read, so I'd probably be less apt to use it. Jan 30, 2011 at 22:44
3

You don't really need to use all three check and if you want a positive integer you might want to do the opposite of what is in your code:

if(is_numeric($i) && $i >= 0) { return true; }

Check Sören's answer for more information concerning the difference between is_int() and is_numeric()

0
3
if(preg_match('/^[1-9]\d*$/',$i)) {
   //Positive and > 0
}
0
3

Rather than checking for int OR string with multiple conditions like:

if ( ctype_digit($i) || ( is_int($i) && $i > 0 ) )
{
    return TRUE;
}

you can simplify this by just casting the input to (string) so that the one ctype_digit call will check both string and int inputs:

if( ctype_digit( (string)$i ) )
{
    return TRUE;
}
0
2

In addition to all the other answers: You are probably looking for ctype_digit. It looks for a string containing only digits.

2

Definition:

!A = !is_numeric($i)
B = $i < 1
!C = $i != round($i)

Then...

!is_numeric($i) || $i < 1 || $i != round($i) is equal to !A || B || !C

So:

!A || B || !C = !A || !C || B

Now, using the deMorgan theorem, i.e. (!A || !C) = (A && C), then:

!A || !C || B = (A && C) || B

Now, note that A && C = is_numeric($i) && $i == round($i), but if $i == round($i) is TRUE, then is_numeric($i) is TRUE as well, so we can simplify A && C = C so,

(A && C) || B = C || B =

$i == round($i) || $i < 1

So you just need to use:

$i = $user_input_value;
if ($i == round($i) || $i < 1) {
  return TRUE;
}
2

To check for positive integer use:

$i = $user_input_value;
if (is_int($i) && $i > 0) {
  return true; //or any other instructions 
}

OR

$i = $user_input_value;
if (!is_int($i) || $i < 1) {
  return false; //or any other instructions 
}

Use the one that fits your purpose as they are the same. The following examples demonstrate the difference between is_numeric() and is_int():

is_numeric(0);     // returns true
is_numeric(7);     // returns true
is_numeric(-7);    // returns true
is_numeric(7.2);   // returns true
is_numeric("7");   // returns true
is_numeric("-7");  // returns true
is_numeric("7.2"); // returns true
is_numeric("abc"); // returns false

is_int(0);     // returns true
is_int(7);     // returns true
is_int(-7);    // returns true
is_int(7.2);   // returns false
is_int("7");   // returns false
is_int("-7");  // returns false
is_int("7.2"); // returns false
is_int("abc"); // returns false
1
  • 2
    is_int checks variable type. It is not applicable to user's input because in most cases it is string.
    – Kirzilla
    Feb 4, 2014 at 13:27
2

Laravel 4.2 Validation rule for positive number

It takes only positive numbers including float values.

public static $rules = array(
    'field_name' => 'required|regex:/^\d*\.?\d*$/'
);

e.g:20,2.6,06

0
1

The first example is using round to verify that the input is an integer, and not a different numeric value (ie: a decimal).

is_int will return false if passed a string. See the PHP manual examples for is_int

1

All these answers overlook the fact that the requestor may checking form input.
The is_int() will fail because the form input is a string.
is_numeric() will be true also for float numbers.
That is why the $i == round($i) comes in as it checks for the input being a whole number.

1
  • Saying "All these answers" is a stretch. I see some answers prior to yours that use regular expressions, for example. Oct 30, 2018 at 16:48
1

Ok, I know this thread is really old but I share @Jeffrey Vdovjak's opinion: since I was able to find it, it might still help someone else out there.

php's gmp_sign() might be another easy way to check. It works for integer and numeric strings, and returns 1 if a is positive, -1 if a is negative, and 0 if a is zero.

So:

// positive
echo gmp_sign("500") . "\n";

// negative
echo gmp_sign("-500") . "\n";

// zero
echo gmp_sign("0") . "\n";

will output:

1
-1
0

See function manual at http://php.net/manual/en/function.gmp-sign.php

P.S. You'll need to have php_gmp.dll enabled in your .ini file.

1

This's my solution, hope helpful :

if (is_numeric($i) && (intval($i) == floatval($i)) && intval($i) > 0)
   echo "positive integer";

i check if string is numeric, second check to sure it's integer and third to sure it positive

0

If you use "is_int" the variable must be integer, so it can't be a float value. (no round needed).

0
if(isset($i) && is_int($i) && $i >= 0){ //0 is technically a postive integer I suppose
    return TRUE; //or FALSE I think in your case.
}
0

I would do something like this:

if ((int) $i > 0) {
    // this number is positive
}

The number gets typecast to a positive or negative number depending on the minus sign being at the front. Then compares the typecast number to being greater than 0 to determine if the number is positive.

1
  • The question is to test if a value is a positive integer. Your proposed solution will return true for any value which when cast to an integer results in a positive value including, but not limited to, positive float values and the boolean literal true. Oct 30, 2018 at 16:43
0

I know this is an old question, but the top answers here did not take into account leading zeroes. And if you are in search of a way to check for positive integers without leading zeroes (think of default autoincremented values, e.g. MySQL ID columns, starting from 1) that might also be numeric strings (contained in a URL, such as an HTTP GET parameter), here are two alternatives:

function isNumericId($input): bool
{
    return ctype_digit($input) && $input[0] != 0;
}

Using a regular expression:

function isNumericId($input): bool
{
    return preg_match("/^[1-9][0-9]*$/", $input) === 1;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.