PHP - 使用哪個條件測試? (PHP - Which conditional test to use?)


問題描述

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 BenzMatsLindhJuan JEren)

參考文件

  1. PHP ‑ Which conditional test to use? (CC BY‑SA 2.5/3.0/4.0)

#if-statement #PHP






相關問題

Python 和 if 語句 (Python and if statement)

Ruby 一種在條件下執行函數的巧妙方法 (Ruby a clever way to execute a function on a condition)

為什麼我的 php 代碼繞過了一些 if 語句? (Why is my php code bypassing a few if statements?)

為什麼“如果”不是C中的表達式 (Why isn't "if" an expression in C)

如何對此查詢進行選擇案例? (How can I do select case to this query?)

我應該使用方法還是常量標誌? (Should I use methods or constant flags?)

PHP - 使用哪個條件測試? (PHP - Which conditional test to use?)

如果日期較新,則將日期從一個數據幀替換為另一個數據幀 (Replace date from one dataframe to another if it's newer)

BASH:在 for 循環中使用 continue (BASH: Using a continue in a for loop)

有沒有辦法從 Tableau 中的 regexp_match 語句中排除某些關鍵字? (Is there a way to exclude certain keywords from a regexp_match statement in Tableau?)

Excel 如果單元格為空白單元格總數的空白單元格總數 (Excel If cell is blank sum number of blank cells for a total)

使用另一個數據框的條件創建一個新列 (Create a new column with a condition of another dataframe)







留言討論