很多人对于 PHP 的 empty(),isset()及 is_null() 三个函数的用法比较模糊,网上的资料也很多,但未必能讲的清楚,下面给出一个测试实例,对于理解这三个函数的区别会有很大的好处。 测试的类型如下: ? php$a ; $b = false ; $c = '' ; $d = 0 ; $e = null
很多人对于 PHP 的 empty(),isset() 及 is_null() 三个函数的用法比较模糊,网上的资料也很多,但未必能讲的清楚,下面给出一个测试实例,对于理解这三个函数的区别会有很大的好处。
测试的类型如下:
<span></span><span>php $a</span><span>;</span><span> $b </span><span>=</span><span>false</span><span>;</span><span> $c </span><span>=</span><span>''</span><span>;</span><span> $d </span><span>=</span><span>0</span><span>;</span><span> $e </span><span>=</span><span>null</span><span>;</span><span> $f </span><span>=</span><span> array</span><span>();</span><span>?></span>
empty()
<span></span><span>php var_dump</span><span>(</span><span>empty</span><span>(</span><span>$a</span><span>));</span><span> var_dump</span><span>(</span><span>empty</span><span>(</span><span>$b</span><span>));</span><span> var_dump</span><span>(</span><span>empty</span><span>(</span><span>$c</span><span>));</span><span> var_dump</span><span>(</span><span>empty</span><span>(</span><span>$d</span><span>));</span><span> var_dump</span><span>(</span><span>empty</span><span>(</span><span>$e</span><span>));</span><span> var_dump</span><span>(</span><span>empty</span><span>(</span><span>$f</span><span>));</span><span>?></span><span> // 输出 bool(true) bool(true) bool(true) bool(true) bool(true) bool(true)</span>
从代码中可以看出,只要数据类型是否为空或假,empty()就输出true。
isset()
<span></span><span>php var_dump</span><span>(</span><span>isset</span><span>(</span><span>$a</span><span>));</span><span> var_dump</span><span>(</span><span>isset</span><span>(</span><span>$b</span><span>));</span><span> var_dump</span><span>(</span><span>isset</span><span>(</span><span>$c</span><span>));</span><span> var_dump</span><span>(</span><span>isset</span><span>(</span><span>$d</span><span>));</span><span> var_dump</span><span>(</span><span>isset</span><span>(</span><span>$e</span><span>));</span><span> var_dump</span><span>(</span><span>isset</span><span>(</span><span>$f</span><span>));</span><span>?></span><span> // 输出 bool(false) bool(true) bool(true) bool(true) bool(false) bool(true)</span>
可以看出isset()只能用来判断是否为NULL和未定义。
is_null()
文章摘自 php empty(), isset(), is_null() 实例测试