The Comparison Operator == (Equality operator) and === (Identity Operator) are used to compare two values. They are also known as the loosely equal (==) operator and the strict identical (===) operator.
Symbol | Name | Example | Output |
---|---|---|---|
== | Equality | $a == $b | TRUE if $a is equal to $b after type juggling |
=== | Identity | $a === $b | TRUE if $a is equal to $b, and both are of the same type |
PHP Operators: There are lots of operators in PHP but == and === operator performs similar kind of task strictly or casually.
- If operands are of different type then == and === will produce different results.The speed of the operators will be different in this case as == will perform type conversion and then do the comparison.
- If operands are of same type then both == and === will produce same results. The speed of both operators is almost identical in this case as no type conversion is performed by any of the operators.
Equality operator == converts the data type temporarily to see if its value is equal to the other operand, whereas === (the identity operator) doesn’t need to do any type casting and thus less work is done, which makes it faster than ==.
Example 1:
php
<?php // 0 == 0 -> true as first type // conversion is done and then // checked if it is equal or not var_dump(0 == "a" ); // 1 == 1 -> true var_dump( "1" == "01" ); // 10 == 10 -> true var_dump( "10" == "1e1" ); // 100 == 100 -> true var_dump(100 == "1e2" ); // 0 === "a" -> false in this type // conversion is not done only // checking is there if they are // equal or not var_dump(0 === "a" ); // "1" === "01" -> false var_dump( "1" === "01" ); // "10" === "1e1" -> false var_dump( "10" === "1e1" ); // 100 == "1e2" -> false var_dump(100 === "1e2" ); switch ( "a" ) { case 0: echo "In first case" ; break ; // Never reached because "a" is already // matched with 0 as in switch == is used case "a" : echo "In second case" ; break ; } ?> |
Output:
bool(true) bool(true) bool(true) bool(true) bool(false) bool(false) bool(false) bool(false) In first case
Example 2:
php
<?php // TRUE - same as (bool)1 == TRUE var_dump(1 == TRUE); // TRUE - same as (bool)0 == FALSE var_dump(0 == FALSE); // FALSE - not same 1 and TRUE as // 1 is integer and TRUE is boolean var_dump(1 === TRUE); // FALSE - not same 0 and FALSE as 0 // is integer and FALSE is boolean var_dump(0 === FALSE); ?> |
Output:
bool(true) bool(true) bool(false) bool(false)
Note: The === operator performs a ‘typesafe comparison’, it will only return true only if both operands have the same type and value whereas if only value is to be compared == is used.