Definition:
isset — Determine if a variable is set and is not NULL
empty — Determine 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';
?>