isset() and empty() in PHP

Definition:

issetDetermine if a variable is set and is not NULL

emptyDetermine whether a variable is empty

 


用以下方法檢查一個表單域是否填寫並且不是空格:

if(isset($_POST[myField]) && $_POST[myField] != "") {
Do my PHP code
}

更好的方法

(

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)以上變量都被認爲是empty

):
if(!empty($_POST[myField])) {
Do my PHP code
}

 

以下代碼幫助更好的理解isset() and empty()

<?php
if (isset($var1)) echo '<p>var1 isset';
else echo '<p>var1 is not set';
if (empty($var1)) echo '<br>var1 is empty';
else echo '<br>var1 is not empty';

$var2 = '';
if (isset($var2)) echo '<p>var2 isset';
else echo '<p>var2 is not set';
if (empty($var2)) echo '<br>var2 is empty';
else echo '<br>var2 is not empty';

$var3 = 'something';
if (isset($var3)) echo '<p>var3 isset';
else echo '<p>var3 is not set';
if (empty($var3)) echo '<br>var3 is empty';
else echo '<br>var3 is not empty';
?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章