is_int and GET or POST

后端 未结 10 1280
傲寒
傲寒 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.

提交回复
热议问题