Some unusual comparison operations in PHP

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.

Popularity: 4% [?]

Tags:

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

Related Posts

» Google PageRank Update…This blog is PR6 now
» Visitor Overview of last 6 days -Thanks a lot for your Love !!!!
» Date or Time Comparison in PHP
» Canada’s postal code validation in PHP

5 Comments on “Some unusual comparison operations in PHP”

  • th wrote on 17 May, 2008, 18:28

    It’s not weird at all.

  • Roshan wrote on 18 May, 2008, 5:08

    he he…..ya it’s not weird..but it’s pretty unusual…

  • php-web-developer wrote on 20 May, 2008, 7:19

    it’s pretty unusual…

  • Technology Blog wrote on 21 May, 2008, 11:28

    You took 2 hrs for this??

  • AgLiAn wrote on 24 July, 2008, 12:05

    try

    var_dump(0 === “c”);

    “===” is checking if your values is the same type of data

Write a Comment

 


Copyright © 2009 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.