Why does is_int
always return false in the following situation?
echo $_GET[\'id\']; //3
if(is_int($_GET[\'id\']))
echo \'int\'; //not execut
Checking for integers using is_int($value)
will return false for strings.
Casting the value -- is_int((int) $value)
-- won't help because strings and floats will result in false positive.
is_numeric($value)
will reject non numeric strings, but floats still pass.
But the thing is, a float cast to integer won't equal itself if it's not an integer. So I came up with something like this:
$isInt = (is_numeric($value) && (int) $value == $value);
It works fine for integers and strings ... and some floating numbers.
But unfortunately, this will not work for some float integers.
$number = pow(125, 1/3); // float(5) -- cube root of 125
var_dump((int) $number == $number); // bool(false)
But that's a whole different question.
Because $_GET['id']
is a string like other parts of query string. You are not converting it to integer anywhere so is_int
return false.
Because HTTP variables are always either strings, or arrays. And the elements of arrays are always strings or arrays.
You want the is_numeric
function, which will return true for "4"
. Either that, or cast the variable to an int $foo = (int) $_GET['id']
...
How i fixed it:
$int_id = (int) $_GET["id"];
if((string)$int_id == $_GET["id"]) {
echo $_GET["id"];
}
Because $_GET is an array of strings.
To check if the get parameter contains an integer you should use is_numeric()
It's probably stored as a string in the $_GET, cast it to an int.