比较具有相同想法的 2 个不同条件

Compare 2 differents conditions with the same idea

我有一个问题:$value !=''!isset($value) 之间有什么区别?

isset() will tell you about the existence of the variable and is not NULL.

empty() can tell you about both, existence of the variable & the value of the variable.

例如

$var1  = "";
echo isset($var1);

输出:- 真

因此,要检查变量是否已设置,请使用 isset(),如果要检查变量的值是否不是 null/empty,请使用 empty().

$value != '' 表示您正在检查 $value 是否不是空字符串。

!isset($value)判断一个变量$value是否未设置,是NULL

阅读这些链接以获取有关 issetempty

的更多信息

What's the difference between 'isset()' and '!empty()' in PHP?

http://php.net/manual/en/function.isset.php

http://php.net/manual/en/types.comparisons.php

$value != ''!isset($value) 在实际使用中的主要区别在于,您可以像这样使用 isset()

if(!isset($value)){
    echo '$value is not declared or is equal to null';
}

如果 $value 没有实际设置,那么您将不会收到 isset() 的通知。如果你做了这样的事情:

if($value != ''){
    echo $value." is not equal to nothing"; 
}

如果未设置 $value 那么这将导致 PHP 中出现一条通知,解释 $value 尚未声明。

需要注意的是 isset() 将检查变量是否已声明但不会检查它是否不等于 ''


但是empty()呢?

此处难题的另一部分是 empty(),它将检查变量是否已声明且不等于 ''。你可以这样做:

if(!empty($value)){
    echo 'We know that $value is declared and not equal to nothing.';
}

这与这样做是一样的:

if(isset($value) && $value != ''){
    echo 'We know that $value is declared and not equal to nothing.';
}

进一步阅读:

isset() - PHP docs

empty() - PHP docs

isset,空支票 - similar question

Why check both isset and empty?

所有这些示例都适用于 PHP 5.3+

$variable != '' 只是检查变量是否为空字符串值(或 null 因为 '' == null),如果变量未定义,将显示通知。

!isset($variable) 检查变量是否已定义,如果不是 returns true,则不会显示 error/notice。


但请注意,即使定义了变量,isset 也可能 return 为假

$variable = null;
var_dump(isset($variable));  // prints false

To check if variable is truly defined 在当前范围内,使用 'array_key_exists' 和 'get_defined_vars'

$variable = null;
var_dump(array_key_exists('value', get_defined_vars()));  // prints true