在php中,($myvariable==0)
当$ myvariable为零时,表达式的值为true;当$ myvariable为null时,这个表达式的值也是真的。我如何排除第二种情况?我的意思是我希望表达式只有在$ myvariable为零时才为真。当然我可以写PHP认为null等于零
($myvariable!=null && $myvariable==0)
但有没有其他优雅的方式来做到这一点?
在php中,($myvariable==0)
当$ myvariable为零时,表达式的值为true;当$ myvariable为null时,这个表达式的值也是真的。我如何排除第二种情况?我的意思是我希望表达式只有在$ myvariable为零时才为真。当然我可以写PHP认为null等于零
($myvariable!=null && $myvariable==0)
但有没有其他优雅的方式来做到这一点?
$myvariable === 0
详细了解comparison operators的。
$myvariable===0
$a === $b
相同TRUE,如果$ a等于$ b,并且它们是相同类型的
有一个is_null
功能,但是这将只需更换你的$myvariable!=null
第二个解决方案将不能工作。 ===
operator是解决您的问题。
使用php函数is_null()函数以及===
运算符。 !==
也符合您的期望。
您提出一个深刻的问题:表达何时应该是真的?
下面我会解释一下为什么你在做什么不行,如何来修复它。
在许多语言中null
,0
和空字符串(""
)都计算为假,这可以使if
语句比较简洁的,直观的,但null
,0
,并且""
也都不同的类型。他们应该如何比较?
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告诉我们,在这种转换中,null
和0
都被认为是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,而不是像==
运算符那样执行类型转换。
希望这会有所帮助。
如果你的零可能是一个字符串,你也应该considere检查“零字符串”
($myvariable === 0 || $myvariable === '0')
要识别为空或零由:
is_int($var)
如果一个变量是一个数字或数字字符串。要识别零,使用is_numeric($var)
也是解决或使用$var === 0
is_null($var)
如果一个变量是NULL
对于我来说,我发现这个soulution和它的作品对我来说:
if ($myvariable == NULL) {
codehere...
}
我哈德在我的一个项目中遇到了类似的问题,只有一点点区别,那就是我还使用值ZERO作为我的条件的有效值。这里是我如何使用简单的逻辑将NULL从零和其他值分开。
if (gettype($company_id) === 'NULL') {
$company = Company::where('id', Auth::user()->company_id)->first();
} else {
$company = Company::where('id', $company_id)->first();
}
除非$ myVariable是一个漂浮在这种情况下,$ MYVARIABLE === floatval(0) – AndyClaw 2015-05-20 14:59:31