Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In the cases where equality comparisons would give the same result as strict equality comparisons, which of the two should be used?

To use an example, should it be $name == "John Doe" or $name === "John Doe"?

I'd guess that equality comparisons would perform worse as they would do some kind of type casting.

p.s. I know that the performance gain of choosing one over the other would be negligible, if any. It's a question of principle.

like image 992
Emanuil Rusev Avatar asked Jan 22 '13 16:01

Emanuil Rusev


People also ask

What is the difference between equality and strict equality?

The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.

Why would you use === instead of ==?

== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.

What is the difference between == and === operators?

KEY DIFFERENCES: = is called as assignment operator, == is called as comparison operator whereas It is also called as comparison operator. = does not return true or false, == Return true only if the two operands are equal while === returns true only if both values and data types are the same for the two variables.

What are equality comparisons?

To summarize comparison of equality is used to show that two things, people are similar. There is no difference between the subject and the object. It can be used with adjectives, adverbs and nouns.


1 Answers

You don't really need to check for === in most of your code, if you carefully live with the fact that you're not using a strongly typed language, but that should be a constant think when you write PHP code.

I usually use ==, reserving === to what the PHP manual suggests (i.e. strpos() calls and similars).

Here's some empirical benchmarks I run. Maybe I should switch to === ;-)

$start = microtime(true);

for($i = 0; $i < 1000000; $i++) {
    if("1" === 1); 
}

$end = microtime(true);

echo number_format($end - $start,5,',','.') . " seconds";

// 0,06117 seconds for "thestring" === "thestring"
// 0,07601 seconds for "thestring" == "thestring"

// 0,05154 seconds for "1" === 1
// 0,09041 seconds for "1" == 1
like image 99
napolux Avatar answered Dec 01 '22 21:12

napolux