top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between == and === in PHP?

+1 vote
1,009 views
What is the difference between == and === in PHP?
posted Jun 25, 2014 by Gowri Sankar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
In PHP === identical operator is really cool feature it let's you check whether the values are equal or not and also to check whether they are of same type or not?
But == equality operator only check whether the values are equal.
________________________________________________________
Let's understand with example

if(2=="2") then echo Same  
else Not same type
// Output would be Not same type. Why? Because 2 is an Integer and "2" is string
whereas
if(2==="2") echo Same
else Not same type
//Output  would be Same, as ultimately it's checking whether 2 is equal to 2 but not checking their data type.

2 Answers

+1 vote

Both == and === are equality operator and check if the left and right values are equal. But, the === operator actually checks to see if the left and right values are equal, and also checks to see if they are of the same variable type (like whether they are both booleans, ints, etc, remember in PHP variable type is defined at the time of the usage).

Practical use

if (is_str_exist($a, $b) == false) // bad code
{
// do something 
}

Now suppose is_str_exist returns falls if b or a is null, returns position of the string $a within $b which can be zero also but as it is == operator so the false == false is true and 0 == false is also true. Correct code should be

if (is_str_exist($a, $b) === false) // bad code
{
// do something 
}
answer Jun 25, 2014 by Salil Agrawal
+1 vote

== operator just checks to if the left and right values are equal.
But , the === operator checks to if the left and right values are equal, and also checks to both are of the same variable type

answer Jul 17, 2014 by Pradeep Kumar
...