PHP and Triple Equals (===)

Gilbert Pellegrom
Gilbert Pellegrom’s Blog
1 min readSep 28, 2010

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.

So the triple equals not only compares the values of the variables but also their types. Simple right.

So why is this interesting or useful? Well imagine for instance you have a function that returns false when it fails, but returns a number when it succeeds. For example:

function example(){ if(...){ return $val; } return false; }

Now imagine the function returned a 0 (not a fail just the number zero) and you were comparing it like:

if(example() == false)

The comparison would be true. Why? Because as far as PHP is concerned `,””andfalse` all return false when compared using == (because their values are all the same). However if you did:

if(example() === false)

Then the comparison would only return true when the function returned the type false. If the function returned `` then the comparison would return false.

Hopefully your still with me and have got the basic idea that the 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.

--

--

Gilbert Pellegrom
Gilbert Pellegrom’s Blog

Software Engineer from Scotland. Founder of @Dev7studioshq. Web Developer at @dliciousbrains.