Main Content

Assignment, equality and identity in PHP

Archive - Originally posted on "The Horse's Mouth" - 2005-08-08 17:45:28 - Graham Ellis

In PHP, you'll find that there's an = operator (that's one = sign), an == operator (that's two equals signs) and an === operator (triple equals). The single = sign is an assignment - it tells PHP to work out the expression to the right of the = sign and save it to the variable / location named on the left. Both == and === perform comparisons - so what's the difference?

== (double equals) is an equality test - it checks whether the values to the left and right of the == operator have the same value - for example, it could check if they're both the value 10. It will return a true value, though, if you compare the integer 10 to the floaring point number 10.0, or if you compare either of those to the string "10.00" ... they're all the value 10, after all!

=== (triple equals) is an identity operator which checks if the values to the left and the right of the === operator have the same value AND are of the same type, so it can only return a true value if you compare two integers or two floats or two strings ... it is bound to return a false value if you compare a float to an integer, even if they both contain the value 10.

Example:


<?php
$first = 10;
$second = 10.0;
$third = "10";

if ($first == 10) print "One";
if ($second == 10) print "Two";
if ($third == 10) print "Three";

if ($third === 10) print "Four";
if ($second === 10) print "Five";
if ($first === 10) print "Six";
?>


Will print out
OneTwoThreeSix