2012-01-31 94 views
13

我一直在寫我的「如果這個變量不爲空」之類的語句,因此最好的做法:不空if語句

if ($var != '') { 
// Yup 
} 

但是我問,如果這是正確的,它沒有對我造成了一個問題。這裏是我在網上找到的答案:

if (!($error == NULL)) { 
/// Yup 
} 

這實際上看起來比我的方法更長,但是更好嗎?如果是這樣,爲什麼?

+4

[is_null](http://php.net/manual/en/function.is-null.php)可以很好地使用。 – 2012-01-31 00:53:34

+1

'if(empty($ var))'或'if(is_null($ var))'似乎對我更好 – 2012-01-31 00:56:03

+0

我同意kingdm。 'empty()'檢查null或空值。 – James 2012-01-31 00:59:07

回答

26

不是:

if (!($error == NULL)) 

簡單地做:

if ($error) 

有人會認爲,首先是更加清晰,但它實際上更多的誤導。原因如下:

$error = null; 

if (!($error == NULL)) { 
    echo 'not null'; 
} 

這個按預期工作。然而,在未來五年值將具有相同和(許多,意想不到的)行爲:

$error = 0; 
$error = array(); 
$error = false; 
$error = ''; 
$error = 0.0; 

第二個條件if ($error)使得它更清楚地表明型鑄造參與。

如果程序員想要求的值實際上是NULL,他應該用嚴格的比較,即if ($error !== NULL)

+0

非常酷。謝謝! – 2012-01-31 01:45:19

+0

請注意,如果您嘗試檢查的變量不存在並且因此爲空,您可能會遇到if($ error)方法的錯誤。 – 2017-12-10 20:53:41

0

爲什麼就是不

if (!$var) 

+0

該變量可能存在,雖然 – 2012-01-31 01:02:58

+2

那麼是什麼?您的問題沒有指定 – dynamic 2012-01-31 01:33:47

+0

當值爲0時不適用於'int'。'if(0)'將返回false。 – 2017-02-28 04:22:12

0

有辦法:

<?php 

error_reporting(E_ALL); 

$foo = NULL; 
var_dump(is_null($inexistent), is_null($foo)); 

?> 

另:

<?php 

$var = ''; 

// This will evaluate to TRUE so the text will be printed. 
if (isset($var)) { 
    echo "This var is set so I will print."; 
} 
?> 

要檢查它是否是空的:

<?php 
$var = 0; 

// Evaluates to true because $var is empty 
if (empty($var)) { 
    echo '$var is either 0, empty, or not set at all'; 
} 

// Evaluates as true because $var is set 
if (isset($var)) { 
    echo '$var is set even though it is empty'; 
} 
?> 
1

這是好事,知道什麼是您的變量,特別是如果你正在檢查未初始化VS空或Na VS真或假VS空或0

因此,如由webbiedave提到的,如果檢查空,使用

$error !== null 
$error === null 
is_null($error) 

如果檢查initilized,如shibly SA ID

isset($var) 

如果檢查真或假,或0,或空字符串

$var === true 
$var === 0 
$var === "" 

我只用爲空'的和無聲,因爲字符串函數往往是不一致的。如果檢查空

empty($var) 
$var // in a boolean context 

// This does the same as above, but is less clear because you are 
// casting to false, which has the same values has empty, but perhaps 
// may not one day. It is also easier to search for bugs where you 
// meant to use === 
$var == false 

如果未初始化的語義是相同的如上述的值中的一個,則在開始時該值初始化變量。

$var = '' 
... //some code 

if ($var === '') blah blah.