問題描述
PHP ‑ 使用哪個條件測試? (PHP ‑ Which conditional test to use?)
這兩個表達式是否等效(我的意思是“我可以用第二個替換第一個):
if ($var) { ... }
和
if (!empty($var)) { ... }
我覺得有區別,但我理性不能說是哪一個。
對我來說,第一個評估 $var 是真還是假,我可能是錯的,但“假”評估意味著 $var 是假(布爾),空(字符串,對象或數組)、0 值(int、float 或 string)或未定義……這就是“空”函數的工作方式(http://php.net/manual/en/function.empty.php)。
如果這些測試是等效的(至少在特定情況下) ,哪個更好用(可讀性,性能,維護,...)?
謝謝
參考解法
方法 1:
They differ in that for your second example, $var
doesn't have to be set before using it. In the first case, if $var
isn't set, a notice will be generated, while in the second example, it won't.
This can be useful for values submitted by users inside the $_GET
and $_POST
superglobals (.. and for $_COOKIE
and $_SERVER
).
// will generate a notice if there is no `foo` in the query string
if ($_GET['foo'])
// will not generate a notice, even if the key is not set
if (!empty($_GET['foo']))
方法 2:
!empty($var)
Determine whether a variable is considered to be not empty. A variable is considered not empty if it does exist
or if its value equals TRUE
. empty() does not generate a warning if the variable does not exist.
if ($var) { ... }
You'll test if $var contains a value that's not false ‑‑ 1 is true, 123 is too
Extra:
isset($var)
Using isset(), you'll test if a variable has been set ‑‑ i.e. if any not‑null value has been written to it.
‑
It all depends on what you want to check/test. I do hope it helps.
方法 3:
empty() ‑> If variable not exist or its equals to false empty function returns true.
Imagine that you did not declare $var
if ($var) {
echo '1';
}
else {
echo '2';
}
Output will be:
NOTICE Undefined variable: var on line number *
If you use empty:
if (!empty($var)) {
echo 1;
}
else {
echo 2;
}
Output will be:
2
Also the following values are considered to be empty
$var = 0;
$var = "";
$var = false;
$var = null;
Also check isset() function Php.net isset
(by Unkle Benz、MatsLindh、Juan J、Eren)