How to verify if $_GET exists?

╄→гoц情女王★ 提交于 2019-11-28 05:38:15

You can use isset function:

if(isset($_GET['id'])) {
    // id index exists
}

You can create a handy function to return default value if index doesn't exist:

function Get($index, $defaultValue) {
    return isset($_GET[$index]) ? $_GET[$index] : $defaultValue);
}

// prints "invalid id" if $_GET['id'] is not set
echo Get('id', 'invalid id');

You can also try to validate it at the same time:

function GetInt($index, $defaultValue) {
    return isset($_GET[$index]) && ctype_digit($_GET[$index])
            ? (int)$_GET[$index] 
            : $defaultValue);
}

// prints 0 if $_GET['id'] is not set or is not numeric
echo GetInt('id', 0);
   if (isset($_GET["id"])){
        //do stuff
    }

Normally it is quite good to do:

echo isset($_GET['id']) ? $_GET['id'] : 'wtf';

This is so when assigning the var to other variables you can do defaults all in one breath instead of constantly using if statements to just give them a default value if they are not set.

You can use the array_key_exists() built-in function:

if (array_key_exists('id', $_GET)) {
    echo $_GET['id'];
}

or the isset() built-in function:

if (isset($_GET['id'])) {
    echo $_GET['id'];
}

You are use PHP isset

Example

if (isset($_GET["id"])) {
    echo $_GET["id"];
}

Use and empty() whit negation (for test if not empty)

if(!empty($_GET['id'])) {
    // if get id is not empty
}

Please try it:

if(isset($_GET['id']) && !empty($_GET['id'])){
   echo $_GET["id"];
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!