NULL是PHP中的一个特殊值,它表示变量确实包含任何值或变量未定义。未定义的变量或没有值的变量是null类型。
如果为变量分配了NULL值,或者没有给变量分配任何值,或者未使用unset()
function设置了变量,则在PHP中变量将被视为null。
检查变量是否包含NULL?
要检查变量是否包含NULL值,我们使用is_null()函数,如果变量包含NULL值或变量未定义,则返回true(1)。
注意:如果变量没有任何值或未使用unset()
函数设置,则PHP返回通知“ Undefined variable”
示例
Input: $var = NULL; Function call: is_null($var); Output: 1
PHP代码演示NULL,is_null()和 unset()
<?php $var1 = "Hello"; $var2 = NULL; $var3 = 10; $var4 = 20; if(is_null($var1)) print("var1 contains NULL\n"); else print("var1 contains $var1\n"); if(is_null($var2)) print("var2 contains NULL\n"); else print("var2 contains $var2\n"); if(is_null($var3)) print("var3 contains NULL\n"); else print("var3 contains $var3\n"); if(is_null($var4)) print("var4 contains NULL\n"); else print("var4 contains $var4\n"); //取消所有变量设置 unset($var1); unset($var2); unset($var3); unset($var4); if(is_null($var1)) print("var1 contains NULL\n"); else print("var1 contains $var1\n"); if(is_null($var2)) print("var2 contains NULL\n"); else print("var2 contains $var2\n"); if(is_null($var3)) print("var3 contains NULL\n"); else print("var3 contains $var3\n"); if(is_null($var4)) print("var4 contains NULL\n"); else print("var4 contains $var4\n"); ?>
输出结果
var1 contains Hello var2 contains NULL var3 contains 10 var4 contains 20 PHP Notice: Undefined variable: var1 in /home/main.php on line 25 var1 contains NULL PHP Notice: Undefined variable: var2 in /home/main.php on line 28 var2 contains NULL PHP Notice: Undefined variable: var3 in /home/main.php on line 31 var3 contains NULL PHP Notice: Undefined variable: var4 in /home/main.php on line 34 var4 contains NULL