PHP Comparison Operators: Equal vs Identical

May 29th, 2011 by Tony de Jesus

PHP logoOne of the most common mistakes of PHP developers (especially at the beginning) is the tendency to confuse the equal operator (==) with the identical operator (===). Frequently, they decide to use only the equal operator and think that it will work in all cases, until the truth is revealed: it doesn’t.An easy way to understand the difference is by checking the following example:

// Case 1:
if("3" == 3){
     echo "They are equal";
}
else{
     echo "They are different";
}

// It will output: They are equal

// Case 2:
if("3" === 3){
     echo "They are equal";
}
else{
     echo "They are different";
}

// It will output: They are different

By using the equal operator we are checking if the values of the two operands are equal or not. So, in the first case, we are checking if the value of “3” is equal to the value of 3. Bear in mind that PHP tries to convert both operands to same value (“3” is a string with the value 3, and 3 is an integer with value 3, so, both operands have same value and are equal).

On the other hand, the identical operator checks the values as well as the type of operands. So, in the second case, we are checking if the value AND type (string) of “3” is equal to the value AND type (integer) of 3. So, they are not identical.

Do you know any situation where it is more convenient to use the identical instead of the equal operator? Share it in the comments section.

,

 
 
 

Leave a Reply