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
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 as16
, 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 returnsTrue
.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
returnsTrue
andis_int
returnsFalse
: 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 returnTrue
, 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:This will return
True
for16
, but notTrue
for16.5
or16e0
- like this You can filter integers from non-integer numbers.