The importance of a strict comparison

April 2, 2015 1 By addshore

A cloudNow if you have ever come across issues caused by non strict comparisons before then this is going to seem like a piece of cake, but remember, everyone makes mistakes.

Strict equality compares two values for equality where the values must also be the same type. Non strict or loose equality compares values while not caring about their type. Strict equality is almost always the correct comparison to use, and if it is not used when it should be many unexpected things can happen.

This can easily be seen in the PHP code snippet below.

//Non strict comparisons
var_dump(0 == FALSE); // bool(true)
var_dump(0 == 'test'); // bool(true)
var_dump(FALSE == 'test'); // bool(false)

//Strict comparisons
var_dump(0 === FALSE); // bool(false)
var_dump(0 === 'test'); // bool(false)
var_dump(FALSE === 'test'); // bool(false)

Recently when using the Mediafire desktop sync software for windows I came across this very issue. The Mediafire client works in a similar way to other clients such as Dropbox, it creates a sync directory locally and anything that is in that directory will be uploaded to the services cloud storage.

The only problem was that the Mediafire developers had forgotten to use a strict comparison somewhere in their client code and as a result all of my directories with a name that was simply ‘0’ would not be uploaded. I’m very glad that I spotted this issue before deleting my files locally assuming they were on stored away.

I reported the issue to Mediafire in December 2014  and it was fixed by mid February 2015.

Always think about strict comparisons when coding!