不等于 PHP 中的 != 和 !==
我一直这样做: if ($foo !== $bar)
但我意识到 if ($foo != $bar)
也是正确的。
Double =
仍然有效并且一直为我工作,但是每当我搜索 PHP 运算符时,我都找不到有关 double =
的信息,所以我认为我一直都做错了,但无论如何它都有效。我应该只是为了它而将所有 !==
更改为 !=
吗?
I've always done this: if ($foo !== $bar)
But I realized that if ($foo != $bar)
is correct too.
Double =
still works and has always worked for me, but whenever I search PHP operators I find no information on double =
, so I assume I've always have done this wrong, but it works anyway. Should I change all my !==
to !=
just for the sake of it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
==
和!=
不考虑所比较变量的数据类型。因此,这些都将返回 true:===
和!==
do 考虑数据类型。这意味着将字符串与布尔值进行比较永远不会成立,因为它们的类型不同。这些都将返回 false:您应该比较返回可能具有模糊真/假值的值的函数的数据类型。一个著名的例子是
strpos()
:==
and!=
do not take into account the data type of the variables you compare. So these would all return true:===
and!==
do take into account the data type. That means comparing a string to a boolean will never be true because they're of different types for example. These will all return false:You should compare data types for functions that return values that could possibly be of ambiguous truthy/falsy value. A well-known example is
strpos()
:!== 应匹配值和数据类型
!= 仅匹配值而忽略数据类型
!== should match the value and data type
!= just match the value ignoring the data type
$a !== $b
TRUE 如果$a
不等于$b
,或者它们不相等相同类型请参考
http://php.net/manual /en/language.operators.comparison.php
$a !== $b
TRUE if$a
is not equal to$b
, or they are not of the same typePlease Refer to
http://php.net/manual/en/language.operators.comparison.php
您可以在这里找到信息: http://www.php.net /manual/en/language.operators.comparison.php
它很稀缺,因为它直到 PHP4 才添加。不过,您所拥有的很好,如果您知道可能存在类型差异,那么这是一个更好的比较,因为它在比较中测试值和类型,而不仅仅是值。
You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php
It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.