Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The importance of using === instead of == in php! [duplicate]

Today only I have noticed and found out the importance of using === operator. You can see it in the following example:

$var=0;
if ($var==false) echo "true"; else echo "false";  //prints true
$var=false;
if ($var==false) echo "true"; else echo "false";  //prints true
$var=0;
if ($var===false) echo "true"; else echo "false";  //prints false
$var=false;
if ($var===false) echo "true"; else echo "false";  //prints true 

The question is that, are there any situations where it is important to use === operator instead of using == operator?

like image 303
Bakhtiyor Avatar asked Jun 21 '10 12:06

Bakhtiyor


2 Answers

Of course, just one example: array_search()

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Basically if you use any function that returns a value on success but FALSE on failure, you should check the result with === to be sure (otherwise why would there be a big red warning box? ;))


Further examples: next(), current()
or as also mentioned string functions as strpos(), stripos(), etc.

Even substr() although it is not mentioned explicitly:

Returns the extracted part of string or FALSE on failure.

But what if the extracted part is"0"? It also evaluates to FALSE, but it is not an error.

like image 112
Felix Kling Avatar answered Nov 10 '22 20:11

Felix Kling


Always choose === over == except you're absolutely sure you need ==, because == is not transitive. And that in turn is important for your reasoning about your code.

Consider the following code snippet

if ( $a == $b && $b == $c ) {
    // [1] assert: $a == $c
}

Anybody would infer from the if condition that the assertion $a == $c is true because we are so used to the equality relation being transitive. But that doesn't hold for ==, counter example:

$a = "0";
$b = 0;
$c = null;

Now think about how often we make (at times unconsciously) that assumption while writing code. That could lead to serious bugs.

like image 36
wnrph Avatar answered Nov 10 '22 18:11

wnrph