如何验证$ _GET是否存在?

Doo*_*nob 58 html php urlvariables

所以,我有一些看起来有点像这样的PHP代码:

<body>
    The ID is 

    <?php
    echo $_GET["id"] . "!";
    ?>

</body>
Run Code Online (Sandbox Code Playgroud)

现在,当我传递一个ID,http://localhost/myphp.php?id=26它可以正常工作,但如果没有像那样的ID http://localhost/myphp.php它输出:

The ID is
Notice: Undefined index: id in C:\xampp\htdocs\myphp.php on line 9
!
Run Code Online (Sandbox Code Playgroud)

我已经搜索了一种方法来解决这个问题,但我找不到任何方法来检查是否存在URL变量.我知道必须有办法.

Zbi*_*iew 131

你可以使用isset功能:

if(isset($_GET['id'])) {
    // id index exists
}
Run Code Online (Sandbox Code Playgroud)

如果索引不存在,您可以创建一个方便的函数来返回默认值:

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');
Run Code Online (Sandbox Code Playgroud)

您也可以尝试同时验证它:

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);
Run Code Online (Sandbox Code Playgroud)


Mak*_*ita 17

   if (isset($_GET["id"])){
        //do stuff
    }
Run Code Online (Sandbox Code Playgroud)


Sam*_*aye 9

通常这样做很好:

echo isset($_GET['id']) ? $_GET['id'] : 'wtf';
Run Code Online (Sandbox Code Playgroud)

将var分配给其他变量时,您可以在一次调用中默认,而不是不断地使用if语句只是在没有设置时给它们一个默认值.

  • WTF就是一个例子......加上它是`wtf`而不是`wft` (3认同)

Asa*_*aph 6

您可以使用array_key_exists()内置功能:

if (array_key_exists('id', $_GET)) {
    echo $_GET['id'];
}
Run Code Online (Sandbox Code Playgroud)

isset()内置功能:

if (isset($_GET['id'])) {
    echo $_GET['id'];
}
Run Code Online (Sandbox Code Playgroud)


Jul*_*ien 5

使用和empty()否定(用于测试如果不为空)

if(!empty($_GET['id'])) {
    // if get id is not empty
}
Run Code Online (Sandbox Code Playgroud)


Bab*_*aba 5

你是使用PHP isset

if (isset($_GET["id"])) {
    echo $_GET["id"];
}
Run Code Online (Sandbox Code Playgroud)