做什么!==和===在PHP中意味着什么?

时间:2010-11-02 17:29:41

标签: php syntax operator-keyword

  

可能重复:
  How do the equality (== double equals) and identity (=== triple equals) comparison operators differ?
  Reference - What does this symbol mean in PHP?
  php not equal to != and !==

此代码段中的!=====运算符是什么?

if ( $a !== null ) // do something
if ( $b === $a ) // do something

6 个答案:

答案 0 :(得分:13)

他们是身份等价运算符。

1 == 1
1 == "1"
1 === 1
1 !== "1"
true === true
true !== "true"
true == "true"

所有这些都等于真。 另请查看@mbeckish提供的this link

答案 1 :(得分:6)

它们是严格的类型比较运算符。他们不仅检查,还检查类型

在比较数字或字符串时考虑一种情况:

if (4 === 4) // same value and type
{
  // true
}

if (4 == "4") // same value and different type but == used
{
  // true
}

if (4 === "4") // same value but different type
{
  // false
}

这适用于对象和数组。

因此,在上述情况下,您必须明智地选择是使用==还是===

当您确定类型

时,最好使用===

更多信息:

答案 2 :(得分:1)

===还会检查变量的类型。

例如,"1" == 1返回true,但"1" === 1返回false。它对于可能返回0或False(例如strpos)的结构特别有用。

这不能正常工作,因为strpos返回0和0 == false

if (strpos('hello', 'hello world!'))

然而,这可行:

if (strpos('hello', 'hello world!') !== false)

答案 3 :(得分:0)

double =符号是一个比较,并测试左边的变量/ expression / constant是否与右边的变量/ expression / constant具有相同的值。

三元符号是一个比较,看两个变量/表达式/常量是否相等并且具有相同的类型 - 即两者都是字符串或两者都是整数。

同样的概念适用于!==

答案 4 :(得分:0)

如果给定值的类型和值都相同,它们将仅返回true。 例: 1 === 1是真的 “1”=== 1是假的 1 ===“1”是假的 “1”===“1”是真的

其中= =以上所有都是真的

答案 5 :(得分:0)

当您使用两个等号==时,它将检查相同的值。

if( '1' == 1 ) { echo 'yes'; }

上述代码有效,因为它们具有相同的值。

但如果使用三个等号===,它将检查值和数据类型。

因此

if( '1' === 1 ) { /* this will not work */ }

这是因为'1'的数据类型为string,而1integernumber

但你可以这样做 - 我想:D

if( (integer) '1' === 1 ) { echo 'this works'; }

因为我们要将'1'的数据类型更改为integer

相关问题