Tip of the day: Loose comparisons in PHP gives edgy behaviour

This is an occasionally recurring issue: Using loose comparison (i.e. “==”, “!=”), instead of strict (i.e. “===”, “!==”), in PHP can give some unexpected results.

Some of those are pretty logical – like an empty array compared to 0 or false, returns true – but others not quite that logical.


// returns true
"string" == 0;

// returns false, as probably expected of the above as well
"string" === 0; 

I assume this is because the string is typecasted to integer, and (int) “string” will give 0. So as we know how PHP’s typecasting is working, it’s easy to understand why “123string” == 123 will return true as well.

Related reading

Be Sociable, Share!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>