Search code examples
phpstringcomparisonstring-comparisonstrict

Should one use strict comparison in Strings?


I know that for instance, using:

if (in_array('...'), array('.', '..', '...') === true)

Over:

if (in_array('...'), array('.', '..', '...') == true)

Can increase performance and avoid some common mistakes (such as 1 == true), however I'm wondering if there is a reason to use strict comparisons on strings, such as:

if ('...' === '...')

Seems to do the exactly same thing as:

if ('...' == '...')

If someone can bring some light to this subject I appreciate it.


Solution

  • If you know both of the values are guaranteed to be strings, then == and === are identical since the only difference between the two is that === checks to see if the types are the same, not just the effective values.

    However, in some cases you don't know for sure that a value is going to be a string - for example, with things like the $_GET and $_POST variables. Consider the following:

    $_GET['foo'] == ""
    

    The above expression will evaluate to true if foo was passed in as a blank string, but it will also evaluate to true if no value was passed in for foo at all. In contrast,

    $_GET['foo'] === ""
    

    will only evaluate to true if a blank string was explicitly passed in - otherwise the value of $_GET['foo'] might be equivalent to a blank string, but the type would not be since it would actually be an empty value for that index, not a string.