is_int and GET or POST

后端 未结 10 1265
傲寒
傲寒 2020-12-14 10:44

Why does is_int always return false in the following situation?

echo $_GET[\'id\']; //3
if(is_int($_GET[\'id\']))
    echo \'int\'; //not execut         


        
相关标签:
10条回答
  • 2020-12-14 10:53

    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.

    0 讨论(0)
  • 2020-12-14 10:54

    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.

    0 讨论(0)
  • 2020-12-14 10:56

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

    0 讨论(0)
  • 2020-12-14 10:57

    How i fixed it:

    $int_id = (int) $_GET["id"];
    
    if((string)$int_id == $_GET["id"]) {
    echo $_GET["id"];
    }
    
    0 讨论(0)
  • 2020-12-14 11:05

    Because $_GET is an array of strings.

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

    0 讨论(0)
  • 2020-12-14 11:06

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

    0 讨论(0)
提交回复
热议问题