September 27, 2010

Strict comparisons (===) in PHP

Have you ever seen a statement like if ($a === $b) and wondered what the whole triple equals thing is all about? Well it is actually quite simple. Assigning and comparing variables in PHP goes like this:

  • $a = $b —  Assign the value of $b to $a
  • $a == $b —  Compare the values of $a and $b
  • $a === $b  —  Compare the values and types of $a and $b

The triple equals not only compares the values of the variables but also their types. This is known as a "strict" comparison.

So why is this interesting or useful? Well, imagine you want to check if a string contains a substring. You might use the strpos function which returns the position of where the needle exists relative to the beginning of the haystack and returns false if the needle was not found.

For example, say you want to determine if the string "abc" contains the letter "a":

$string = 'abc';
if (strpos($string, 'a')) {
    echo 'We found "a"';
}

The above code will not work as expected. The strpos function will return zero (0) as the letter "a" is the first letter in the string (index 0). In PHP, zero is falsey (treated the same as false) and so the conditional check will fail.

To make this code work, we'd need to do a strict check for the boolean type false:

$string = 'abc';
if (strpos($string, 'a') !== false) {
    echo 'We found "a"';
}

In the above code, as strpos returns zero (integer) and not false (boolean), the conditional check will pass.

Hopefully, you're still with me and have got the basic idea that the strict comparisons (triple equals) in PHP enforces type checking when comparing variables. Check out the PHP type comparison tables to get a better idea of the difference between comparisons.

Looking for more?

Subscribe to my newsletter to get infrequent updates in your inbox. Or follow me on Twitter.