PHP has an intval() function that will convert a string to an integer. However I want to check that the string is an integer beforehand, so that I can give a helpful error message to the user if it’s wrong. PHP has is_int(), but that returns false for string like "2".
PHP has the is_numeric() function, but that will return true if the number is a double. I want something that will return false for a double, but true for an int.
e.g.:
my_is_int("2") == TRUE
my_is_int("2.1") == FALSE
How about using
ctype_digit?From the manual:
The above example will output:
This will only work if your input is always a string:
If your input might be of type
int, then combinectype_digitwithis_int.If you care about negative numbers, then you’ll need to check the input for a preceding
-, and if so, callctype_digiton asubstrof the input string. Something like this would do it: