2009-11-23 91 views
39

在php中,($myvariable==0) 當$ myvariable爲零時,表達式的值爲true;當$ myvariable爲null時,這個表達式的值也是真的。我如何排除第二種情況?我的意思是我希望表達式只有在$ myvariable爲零時才爲真。當然我可以寫PHP認爲null等於零

($myvariable!=null && $myvariable==0) 

但有沒有其他優雅的方式來做到這一點?

回答

0
$myvariable===0 


$a === $b 

相同TRUE,如果$ a等於$ b,並且它們是相同類型的

0

有一個is_null功能,但是這將只需更換你的$myvariable!=null

3

嘗試($myvariable === 0)它不會執行類型強制。

+6

:P猜測我是不是在西部最快的槍... – Skilldrick 2009-11-23 12:10:59

4

使用php函數is_null()函數以及===運算符。 !==也符合您的期望。

9

您提出一個深刻的問題:表達何時應該是真的?

下面我會解釋一下爲什麼你在做什麼不行,如何來修復它。

在許多語言中null0和空字符串("")都計算爲假,這可以使if語句比較簡潔的,直觀的,但null0,並且""也都不同的類型。他們應該如何比較?

This page告訴我們,如果我們有兩個變量進行比較,則變量轉換如下(在第一場比賽退出表)

Type of First Type of Second Then 
null/string string   Convert NULL to "", numerical/lexical comparison 
bool/null  anything   Convert to bool, FALSE < TRUE 

那麼,你是比較空與一個數字。因此,null和數字都被轉換爲布爾值。 This page告訴我們,在這種轉換中,null0都被認爲是FALSE。你的表情現在是false==false,這當然是對的。

但不是你想要的。

This page提供了PHP的比較運算符列表。

Example Name    Result 
$a == $b Equal    TRUE if $a equals $b after type juggling. 
$a === $b Identical   TRUE if $a equals $b, AND they are of the same type. 
$a != $b Not equal   TRUE if $a not equals $b after type juggling. 
$a <> $b Not equal   TRUE if $a not equals $b after type juggling. 
$a !== $b Not identical  TRUE if $a not equals $b, or they are not of the same type. 
$a < $b Less than   TRUE if $a is strictly less than $b. 
$a > $b Greater than  TRUE if $a is strictly greater than $b. 
$a <= $b Less than/equal TRUE if $a is less than or equal to $b. 
$a >= $b Greater than/equal TRUE if $a is greater than or equal to $b. 

第一個比較器是您現在使用的比較。請注意,它執行前面提到的轉換。

使用第二個比較器將解決您的問題。由於null和數字不是相同類型,所以===比較將返回false,而不是像==運算符那樣執行類型轉換。

希望這會有所幫助。

0

如果你的零可能是一個字符串,你也應該considere檢查「零字符串」

($myvariable === 0 || $myvariable === '0') 
5

要識別爲空或零由:

  • is_int($var)如果一個變量是一個數字或數字字符串。要識別零,使用is_numeric($var)也是解決或使用$var === 0

  • is_null($var)如果一個變量是NULL

-1

對於我來說,我發現這個soulution和它的作品對我來說:

if ($myvariable == NULL) { 
    codehere... 
} 
0

我哈德在我的一個項目中遇到了類似的問題,只有一點點區別,那就是我還使用值ZERO作爲我的條件的有效值。這裏是我如何使用簡單的邏輯將NULL從零和其他值分開。

if (gettype($company_id) === 'NULL') { 
     $company = Company::where('id', Auth::user()->company_id)->first(); 
    } else { 
     $company = Company::where('id', $company_id)->first(); 
    }