isset() 与 TYPE 或 VALUE 无关 - 仅与 EXISTENCE 相关。
if ($condition)... 将 VALUE OF THE VARIABLE 评估为布尔值。
if ( isset($condition) )... 将 EXISTENCE OF THE VARIABLE VALUE 评估为布尔值。
isset() 可能为假有两个原因。
首先,因为变量没有设置,所以没有值。
其次,因为一个变量是NULL,这意味着“未知值”,不能被认为是设置,因为它包含“无值”,而且因为很多人使用$v = null来表示与unset($五)。
(请记住,如果您特别想检查 null,请使用 is_null()。)
isset() 通常用于检查可能存在或不存在的外部变量。
例如,如果您有一个名为 page.php 的页面,它有:
ini_set('display_errors', 1);
error_reporting(E_ALL);
if ( $_GET["val"] ) {
// Do Something
} else {
// Do Nothing
}
它适用于以下任何 URL:
http://www.example.com/page.php?val=true // Something will be done.
http://www.example.com/page.php?val=monkey // Something will be done.
http://www.example.com/page.php?val=false // Nothing will be done.
http://www.example.com/page.php?val=0// Nothing will be done.
但是,您将收到此 URL 的错误:
http://www.example.com/page.php
因为 URL 中没有 'val' 参数,所以 $_GET 数组中没有 'val' 索引。
正确的做法是这样的:
if ( isset($_GET["val"]) ) {
if ( $_GET["val"] ) {
// Do Something
} else {
// Do Nothing
}
} else {
// $_GET["value"] variable doesn't exist. It is neither true, nor false, nor null (unknown value), but would cause an error if evaluated as boolean.
}
虽然这有捷径。
您可以使用empty()检查存在和某些布尔条件的组合,
if ( !empty($_GET["val"]) ) {
// Do someting if the val is both set and not empty
// See http://php.net/empty for details on what is considered empty
// Note that null is considered empty.
}
或
if ( isset($_GET["val"]) and $_GET["val"] ) {
// Do something if $_GET is set and evaluates to true.
// See php.net logical operators page for precedence details,
// but the second conditional will never be checked (and therefor
// cause no error) if the isset returns false.
}