tags:

views:

76

answers:

5

Hi,

why always i get false?

even in a this situation:

echo $_GET['id']; //3
if(is_int($_GET['id']))
    echo 'int';
+1  A: 

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.

Sarfraz
doesn't `inval()` always return an int, so isn't the `is_int()` check superfluous?
Tom Haigh
@Tom Haigh: That is just an example, just put up the code so that condition return true, a problem posed by OP. And yes it is redundant; either should be used but I wonder what OP is up to.
Sarfraz
Omg, how stupid is that solution? Sorry, but that makes no sense at all. Casting to `int` within the `is_int()` function is probably the worst example you'll find in here.
GuidoH
@GuidoH why ? he answered the question ?
Chris
That's absolutely no solution! If you cast a variable to `int` within the `is_int()` function, it'll **always** return `true`.
GuidoH
@GuidoH: Who said it is a solution? It is just an example on how to make the condition resolve to true. See my comment for Tom Haigh. But i rather remove that part because it creates confusion for you and the like. And you should mind your language :)
Sarfraz
+8  A: 

why always i get 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 is_numeric() that will correctly recognize the string not perfect: It will also recognize float values (1.23132)

  • 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.

Pekka
keep in mind that e.g. `is_numeric('47.11e5')` returns true. I.e. is_numeric() doesn't only test for integers in decimal representation.
VolkerK
@Volker yup, I just had the same thought. Updated.
Pekka
@Artefacto good job, wasn't aware of that filter! Thanks.
Pekka
A: 

It's probably stored as a string in the $_GET, cast it to an int.

signine
+1  A: 

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

ircmaxell
A: 

Because $_GET is an array of strings.

To check if the get parameter contains an integer you should use is_numeric()

klez