在PHP中不等于!=和!== [英] Not equal to != and !== in PHP

查看:98
本文介绍了在PHP中不等于!=和!==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直这样做:if ($foo !== $bar)

但是我意识到if ($foo != $bar)也是正确的.

But I realized that if ($foo != $bar) is correct too.

双精度=仍然有效并且一直为我工作,但是每当我搜索PHP运算符时,我都找不到关于双精度=的信息,因此我认为我一直做错了,但是无论如何它都能正常工作.我是否应该仅出于此目的将所有!==更改为!=?

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?

推荐答案

==!=不考虑您比较的变量的数据类型.因此,这些都将返回true:

== and != do not take into account the data type of the variables you compare. So these would all return true:

'0'   == 0
false == 0
NULL  == false

===!== 要做考虑了数据类型.这意味着将字符串与布尔值进行比较将从不为真,因为它们的类型不同.这些都将返回false:

=== 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:

'0'   === 0
false === 0
NULL  === false

您应该比较函数的数据类型,这些函数返回的值可能是含糊的真实/错误值.一个著名的例子是strpos():

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():

// This returns 0 because F exists as the first character, but as my above example,
// 0 could mean false, so using == or != would return an incorrect result
var_dump(strpos('Foo', 'F') != false);  // bool(false)
var_dump(strpos('Foo', 'F') !== false); // bool(true), it exists so false isn't returned

这篇关于在PHP中不等于!=和!==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆