What’s the difference between double and triple equals in PHP? PHP supports both double (==) and triple (===) comparison. Then when to use double equal to and when to use triple equal to in our code.
When I first saw the comparison using triple equal to it seems confusing in the beginning but later I understood why triple equality operator is used.
How to check memory usage by a PHP script
Difference Between Double and Triple Equals in PHP
Double equals is also known as type-converting equality. When we use double equal to in our code, it first converts the operands to the same type before comparing the values.
Let’s understand this through example –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/* $a is of int type */ $a = 8; /* $b is of string type */ $b = '8'; if ($a == $b) { echo "Equal"; } else { echo "Not Equal"; } /* Output - Equal */ |
Singleton design pattern in PHP
Abstract Class Vs Interface in PHP
Triple Equals (===) in PHP
Triple equals (strict comparison) compares both values as well as the data type. So let’s check what’s the output of the above script when we use triple equals.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/* $a is of int type */ $a = 8; /* $b is of string type */ $b = '8'; if ($a === $b) { echo "Equal"; } else { echo "Not Equal"; } /* Output - Not Equal (As it compares both values as well as data type)*/ |
Important Points –
PHP is a loosely typed language. Using the double equal operator allows for a loose checking of a variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/* Empty value is assigned */ $a = ''; /* Zero value is assigned */ $b = 0; if ($a == $b) { echo "Equal"; } else { echo "Not Equal"; } /* Output - Equal */ |
Now let’s compare the same value with triple equal to.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/* Empty value is assigned */ $a = ''; /* Zero value is assigned */ $b = 0; if ($a === $b) { echo "Equal"; } else { echo "Not Equal"; } /* output - Not Equal */ |
To avoid such cases in your code try to use triple equals(===).