What is the difference between ==
and ===
?
- How exactly does the loosely
==
comparison work? - How exactly does the strict
===
comparison work?
What would be some useful examples?
What is the difference between ==
and ===
?
==
comparison work?===
comparison work? What would be some useful examples?
As for when to use one over the other, take for example the
fwrite()
function in PHP.This function writes content to a file stream. According to PHP, "
fwrite()
returns the number of bytes written, or FALSE on error.". If you want to test if the function call was successful, this method is flawed:It can return zero (and is considered successful), and your condition still gets triggered. The right way would be:
Difference between
==
and===
The difference between the loosely
==
equal operator and the strict===
identical operator is exactly explained in the manual:Loosely
==
equal comparisonIf you are using the
==
operator, or any other comparison operator which uses loosely comparison such as!=
,<>
or==
, you always have to look at the context to see what, where and why something gets converted to understand what is going on.Converting rules
Type comparison table
As reference and example you can see the comparison table in the manual:
Strict
===
identical comparisonIf you are using the
===
operator, or any other comparison operator which uses strict comparison such as!==
or===
, then you can always be sure that the types won't magically change, because there will be no converting going on. So with strict comparison the type and value have to be the same, not only the value.Type comparison table
As reference and example you can see the comparison table in the manual:
A picture is worth a thousand words:
PHP Double Equals
==
equality chart:PHP Triple Equals
===
Equality chart:Source code to create these images:
https://github.com/sentientmachine/php_equality_charts
Guru Meditation
Those who wish to keep their sanity, read no further.
PHP Variables that have not been declared yet are false.
False is equal to 0, blankstring and empty array and "0".
NAN does not == itself, but it is True.
A fresh class is == to 1.
Hope:
If you are using PHP, Thou shalt not use the double equals operator, always use triple equals.
Few of the examples
P.S.
vs.
PHP is a loosely typed language. Using the double equal operator allows for a loose checking of a variable.
Loosely checking a value would allow for some similar, but not equal, values to equate as the same:
All of these values would equate as equal using the double equal operator.
One example is that a database attribute can be null or "":