为什么我需要php中的isset()函数?

zec*_*ude 12 php post if-statement isset

我试图理解这个之间的区别:

if (isset($_POST['Submit'])) { 
  //do something
}
Run Code Online (Sandbox Code Playgroud)

if ($_POST['Submit']) { 
  //do something
}
Run Code Online (Sandbox Code Playgroud)

在我看来,如果$ _POST ['Submit']变量为true,那么它就被设置了.在这种情况下,为什么我需要isset()函数?

ken*_*ytm 20

因为

$a = array("x" => "0");

if ($a["x"])
  echo "This branch is not executed";

if (isset($a["x"]))
  echo "But this will";
Run Code Online (Sandbox Code Playgroud)

(另见http://hk.php.net/manual/en/function.isset.phphttp://hk.php.net/manual/en/language.types.boolean.php#language.types.boolean .casting)

  • 当`$ a`中没有定义键'x`时,试图访问`$ a ["x"]`也会引发一个`E_Notice`.使用`isset`或`array_key_exists`进行检查可以避免这种情况. (2认同)