Today I was working for a project and a weired comparison operation in PHP got my brain out for 2 hour and after searching in google I could able to figure out the problem and I’m posting here so that you guys who are unaware of this kind of comparison will not suffer in future. First let’s see two examples the unusual comparison in PHP.
var_dump(0 == "c"); //returns true var_dump("5" == "05"); // returns true
As you can see above the two comparison result are unusual. 0==”c” is true which should be acoording to the logic because 0 is not equal to “C” and . But there is unusual comparison rule in PHP which states that,
“If you compare integer with strings then the string is converted to integer”
when “c” is converted into string it becomes 0 and returns true.
Now, let’s look at the second example although the string “5” is not equal to “05” but it returns true. Here is another rule for this
“If you compare two numerical strings, they are compared as numerical value”.
Hence, the second statement compares like 5==5 which is always true.
Overcoming such situation with Identical Operator(“===”) in PHP
Identical operator are represented with three equel signs (===) in PHP. Let’s see what is an identical operator is,
$var1===$var2, it returns true if $var1 is equal to $var2 and $var1 and $var2 are of same type.
Now let’s look at the above comparison operation with identical operator
var_dump(5 === "05"); //false - different type of data var_dump(0 === "d"); //false - different type of data
As, you can see identical operator gives exact result for comparing different type of data.