Can you explain the difference between ==
and ===
, giving some useful examples?
views:
2322answers:
5How do the equality (== double equals) and identity (=== triple equals) comparison operators differ?
== compares the values of variables for equality, type casting as necessary. === checks if the two variables are of the same type AND have the same value.
A full explanation of the differences are available in the PHP manual.
Here's a table I put together showing how some variables compare to each other.
// "===" means that they are identical
// "==" means that they are equal
// "!=" means that they aren't equal.
false null array() 0 "0" 0x0 "0x0" "000" "0000"
false === == == == == == != != !=
null == === == == != == != != !=
array() == == === != != != != != !=
0 == == != === == === == == ==
"0" == != != == === == == == ==
0x0 == == != === == === == == ==
"0x0" != != != == == == === == ==
"000" != != != == == == == === ==
"0000" != != != == == == == == ===
You would use === to test whether a function or variable is false rather than just equating to false (zero or an empty string).
$needle = 'a';
$haystack = 'abc';
$pos = strpos($haystack, $needle);
if ($pos === false) {
echo $needle . ' was not found in ' . $haystack;
} else {
echo $needle . ' was found in ' . $haystack . ' at location ' . $pos;
}
In this case strpos would return 0 which would equate to false in the test
if ($pos == false)
or
if (!$pos)
which is not what you want here.
In regards to Javascript
The === operator works the same as the == operator but requires that its operands have not only the same value, but also the same data type.
For example the sample below will display 'x and y are equal' but not 'x and y are identical'
var x = 4;
var y = '4';
if (x == y) {
alert('x and y are equal');
}
if (x === y) {
alert('x and y are identical');
}
Variables have a type and a value.
- $var = "test" is a string that contain "test"
- $var2 = 24 is an integer vhose value is 24.
When you use these variables (in PHP), sometimes you don't have the good type. For example, if you do
if ($var == 1) {... do something ...}
PHP have to convert ("to cast") $var to integer. In this case, "$var == 1" is true because any non-empty string is casted to 1.
When using ===, you check that the value AND THE TYPE are equal, so "$var === 1" is false.
This is useful, for example, when you have a function that can return false (on error) and 0 (result) :
if(myFunction() == false) { ... error on myFunction ... }
This code is wrong as if myFunction()
returns 0, it is casted to false and you seem to have an error. The correct code is :
if(myFunction() === false) { ... error on myFunction ... }
because the test is that the return value "is a boolean and is false" and not "can be casted to false".
Given x = 5
1) Operator : == is "equal to". x == 8
is false
2) Operator : === is "exactly equal to" (value and type) x === 5
is true, x === "5"
is false