检查变量是否在PHP中设置


Check if variable is set in PHP

所以我想看看用户是否输入了什么:

$test = $_GET["restaurantName"];
if(isset($test))
{
    echo "you inputed something";
    echo "$test";
}
if(!isset($test))
{
    echo "you did not input anything";
    echo "$test";
}
die("The End");

出于某种原因,即使我没有输入任何内容,它仍然会通过第一个if语句,并表示已经输入了某些内容,即使我不输入,我也查看了有关isset()的文档,我很确定这就是应该使用它的方式。

如果您想保持相同的布局样式,就应该这样做。

if(isSet($_GET["restaurantName"])) {
     $test = $_GET["restaurantName"];
}
if(isset($test))
    {
        echo "you inputed something";
        echo "$test";
    } else { //!isset($test)
        echo "you did not input anything";
        echo "$test";
    }

您的问题是您正在设置变量,即使GET不存在。

我个人会怎么做,因为它使代码更短,输出相同:

if(isSet($_GET["restaurantName"])) {
    $test = $_GET["restaurantName"];
    echo "Your input: ".$test;
} else {
    echo "No Input";
}

您正在设置它:$test = $_GET["restaurantName"];isset检查变量是否已设置,而不是包含的变量是否为null或空,您可以使用!empty

你也可以检查isset($_GET["restaurantName"];),但要注意,即使你的url中的get变量是?restaurantName=,它仍然是空的

最好的方法是检查它是否已设置,而不是空字符串:

if(isset($_GET["restaurantName"]) && $_GET["restaurantName"] != "")
{
    echo "you inputed something";
    echo $_GET["restaurantName"];
} else {
    echo "you did not input anything";
}
die("The End");

我还删除了第二个if,因为您可以只使用else子句,而不用检查两次。

一些链接可阅读:http://php.net/manual/en/function.isset.phphttp://php.net/manual/en/function.empty.php

如果此$_GET['restaurantName']来自提交(GET)表单输入,而不是链接中的查询字符串(可能存在也可能不存在),则它将始终被设置。如果用户没有输入任何内容,它将被设置为一个空字符串。您可以使用empty而不是isset进行检查(empty包括对isset的检查)。

if (!empty($_GET['restaurantName'])) {
    echo "you input " . $_GET['restaurantName'];
} else {
    echo "you did not input anything";
}

如果修剪后的条目类似于' ',也可以使用进行检查,这可能是一个好主意

if (!empty($_GET['restaurantName']) && trim($_GET['restaurantName'])) { ...

但这开始更多地涉及到表单验证,这本身就是另一个主题。