Identity and Equivalence
A lot of people don’t seem to know the real difference between the equivalence and identity operators, this short articles aims to change that.
The most common comparison operator has got to be the equivalence operator (==), which, as the name suggest, compares one operand against another to see if they’re equal. If the two operands’ values are loosely equal (by that I mean the values are the same, but the data types needn't be the same) then the test evaluates to true. Let’s take a look at some examples:
For example, strpos returns the index of the first occurrence of a needle within a haystack (basically it returns the index of one string within another), however if the needle cannot be found the functions returns FALSE.
NULL, as you may or may not know is equal to 0 when using the equality comparison operator. So, let’s consider the following example:
In order to overcome this problem we will need to evaluate the two operands using the identity operator (===).
The Identity Operator
The identity operator uses three equal signs and is used to determine if one value is identical to another. This comparison only evaluates to true if the two values are of the same value and data type, rather than the equivalence operator which works solely on the value of the operand.
Let’s see some examples of this:
Finally let’s amend our previous strpos example, this time we’ll use the identify operator to compare the result of strpos.
Found H at index 0", which is the expected result.
I hope this article has helped shine some light onto these easy, but powerful comparison operators. It’s important to remember the differences as it can get you in a world of trouble if you don’t remember NULL == 0 evaluates to true, especially when using functions that can return both 0 and FALSE, such as strpos. To conclude, always remember that for any two expressions,
$a == $b is TRUE if $a is equal to $b.
$a === $b is TRUE if $a is equal to $b, and they are of the same type.
THanks to Salathe for pointing out some stuipid mistakes
Informative article. I think most people will get confused based on the fact I get asked this question a lot. Especially on functions that are capable of returning a zero even though that is a positive return, such as the aforementioned strpos. It's something people should be consciously aware of when coding their scripts as otherwise it's just blind conformity.
|All times are GMT. The time now is 01:58 AM.|
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0