is_int and GET or POST

后端 未结 10 1266
傲寒
傲寒 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 11:06

    Prabably best way to check if value from GET or POST is integer is check by preg_match

    if( preg_match('/^[0-9]+$/', $_GET['id'] ){
       echo "is int";
    }
    
    0 讨论(0)
  • 2020-12-14 11:08

    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)
    0 讨论(0)
  • 2020-12-14 11:14

    You can possibly try the intval() which can be used to test the value of your var. e.g

    If(intval($_GET['ID']==0)
    

    The function will check if the var is integer and return TRUE if not FALSE

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

    The dirty solution I'm using is this:

    $val = trim($_GET['id']);
    $cnd = ($val == (int)$val);
    echo $cnd ? "It's an int" : "Not an int";
    

    Apart from the obvious (ugly code that hides its workings behind specifics of the php engine), does anybody know cases where this goes wrong?

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