Possibl开发者_运维问答e Duplicates:
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 !==
What are the !==
and ===
operators in this code snippet?
if ( $a !== null ) // do something
if ( $b === $a ) // do something
They are identity equivalence operators.
1 == 1
1 == "1"
1 === 1
1 !== "1"
true === true
true !== "true"
true == "true"
All of these equate to true. Also check this link provided by @mbeckish
They are strict type comparison operators. They not only check the value but also the type.
Consider a situation when you compare numbers or strings:
if (4 === 4) // same value and type
{
// true
}
but
if (4 == "4") // same value and different type but == used
{
// true
}
and
if (4 === "4") // same value but different type
{
// false
}
This applies to objects as well as arrays.
So in above cases, you have to make sensible choice whether to use ==
or ===
It is good idea to use ===
when you are sure about the type as well
More Info:
- http://php.net/manual/en/types.comparisons.php
=== also checks for the type of the variable.
For instance, "1" == 1
returns true but "1" === 1
returns false. It's particularly useful for fonctions that may return 0 or False (strpos for instance).
This wouldn't work correctly because strpos returns 0 and 0 == false
if (strpos('hello', 'hello world!'))
This, however, would work :
if (strpos('hello', 'hello world!') !== false)
A double = sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right.
A triple = sign is a comparison to see whether two variables / expresions / constants are equal AND have the same type - i.e. both are strings or both are integers.
The same concept applies for !==
They will only return true if both the type and value of the values given are equivalent. Example: 1 === 1 is true "1" === 1 is false 1 === "1" is false "1" === "1" is true
where as with == all of the above would be true
When you use two equal signs ==
it will check for the same value.
if( '1' == 1 ) { echo 'yes'; }
The above code works because they have the same value.
But if you use three equal signs ===
it will check the value and the data type.
Therefore
if( '1' === 1 ) { /* this will not work */ }
This is because '1'
has a data type of string
while 1
is an integer
or a number
But you could do something like this - I think :D
if( (integer) '1' === 1 ) { echo 'this works'; }
Because we are changing the data type of '1'
to an integer
精彩评论