Question

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.

Was it helpful?

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.

OTHER TIPS

When you can use one or the other choose the strict comparison because:

  1. It has better performance
  2. It prevents unexpected results

When comparing strings you can still have unexpected results because a string could be empty or a variable you think is a string actually is not.

You would never use the comparison of two string literals because it can always be reduced to TRUE or FALSE. For example:

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

is the same as

if (TRUE)

So since you will always be comparing at least one variable you must assume that you can have unexpected results.

You can see benchmark results of various strict vs. loose comparisons at http://net-beta.net/ubench/. I have also ran my own tests and found the same results.

This is a micro optimization, which means you shouldn't go changing existing code because it isn't going to make a noticeable difference, but if you are writing new code you might as well practice using the most efficient techniques.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top