is_int and GET or POST

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 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']...


Why does is_int always return false?

Because $_GET["id"] is a string, even if it happens to contain a number.

Your options:

  • Use the filter extension. filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT) will return an integer typed variable if the variable exists, is not an array, represents an integer and that integer is within the valid bounds. Otherwise it will return false.

  • Force cast it to integer (int)$_GET["id"] - probably not what you want because you can't properly handle errors (i.e. "id" not being a number)

  • Use ctype_digit() to make sure the string consists only of numbers, and therefore is an integer - technically, this returns true also with very large numbers that are beyond int's scope, but I doubt this will be a problem. However, note that this method will not recognize negative numbers.

Do not use:

  • is_numeric() because it will also recognize float values (1.23132)

How i fixed it:

$int_id = (int) $_GET["id"];

if((string)$int_id == $_GET["id"]) {
echo $_GET["id"];
}

Tags:

Php