Home  >  Q&A  >  body text

Check if a PHP string consists only of integers

I'm writing PHP code to validate some data entered by the user, one of which is an integer, I use $_REQUEST["age"] to get it, when I use gettype($ _REQUEST["age"]) == "integer" and is_int($_REQUEST["age"]) both return false when checking if this value is an integer, but when I use Returns true when is_numeric($_REQUEST["age"]). I want to check if the value of a parameter is an integer, am I using the first two functions correctly or am I missing something?

Thanks

NOTE: I tried outputting gettype($_REQUEST["age"]) and it returned me string

P粉788765679P粉788765679417 days ago614

reply all(2)I'll reply

  • P粉293550575

    P粉2935505752023-09-22 16:02:18

    <?
         if(intval($_REQUEST["age"]) > 0):
            echo '整数';
         else:
            echo '其他';
         endif;
    ?>

    reply
    0
  • P粉107772015

    P粉1077720152023-09-22 09:25:38

    Short version:

    Use ctype_digit($_REQUEST['age'])

    Detailed version:

    Your problem is that when you use gettype, $_REQUEST returns a string. Even if the string is semantically an integer, such as 16, it is still a string type, not an integer type variable. The reason you get different results from these two tests is because they test different things:

    • is_numeric Tests whether a string contains an "optional symbol, any number of digits, an optional decimal part, and an optional exponent part", according to PHP documentation. In your case, the string only contains numbers, so the test returns True.
    • is_int Tests whether the variable's type is an integer - but it won't be an integer because it is returned by $_REQUEST.

    This is why is_numeric returns True and is_int returns False: the string only contains numbers (so " numeric"), but is still technically a string type, not an integer type (so not "int"). Of course, is_numeric is not enough for integer testing, because if the string has decimals or uses scientific notation, it will return True, which is a number but not an integer.

    To test whether $_REQUEST is an integer, regardless of the technical type, you can test whether all characters in the string are numbers (and therefore the entire string is an integer). For this you can use ctype_digit:

    ctype_digit($_REQUEST['age'])

    This will return True for 16, but not True for 16.5 or 16e0 - like this You can filter integers from non-integer numbers.

    reply
    0
  • Cancelreply