2014/02/13

PHP isset與empty和is_null比較

isset:判斷變數是否被設定且不為null
empty:判斷變數是否為空值
is_null:檢查變數是否為null

isset與empty差別在於isset能夠辨別變數是否被設定,empty只是判斷變數是否為空值
isset與is_null差別在於isset辨別變數不為null,is_null則是辨別變數是否指向null
empty與is_null差別在於empty會辨別變數為空值,is_null辨別參數是否指向null

程式碼如下:



<?php
 
 $test = null;
 $test1;
 $test2 = "";
 $test3 = "123";

 echo "isset<br>-------<br>";
 var_export(isset($test));
 echo '<br>';
 var_export(isset($test1));
 echo "<br>";
 var_export(isset($test2));
 echo "<br>";
 var_export(isset($test3));
 echo "<br><br><br>";

 //empty
 echo "empty<br>-------<br>";
 var_export(empty($test));
 echo "<br>";
 var_export(empty($test1));
 echo "<br>";
 var_export(empty($test2));
 echo "<br>";
 var_export(empty($test3));
 echo "<br><br><br>";


 //is_null
 echo "is_null<br>-------<br>";
 var_export(is_null($test));
 echo "<br>";
 var_export(is_null($test1));
 echo "<br>";
 var_export(is_null($test2));
 echo "<br>";
 var_export(is_null($test3));
 echo "<br><br><br>";
 

?>









參考資料:
http://tw2.php.net/isset
http://php.net/manual/en/function.empty.php
http://tw2.php.net/is_null
http://php.net/manual/en/function.var-export.php