Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison operator "==" in PHP confusion

Tags:

php

In PHP,

null==0
0=="0"

If you combine these two, you would expect:

null=="0"

But this is not true.

Could someone explain this to me?

like image 911
ericj Avatar asked Dec 12 '22 22:12

ericj


1 Answers

In the first case:

null==0

null evaluates to false , same as 0 which evaluates to false, so both are false and so the comparison returns true.

In second case:

0=="0"

here you are comparing two variables of different type, one is numerical and other string, because you are not using the === operator, PHP cast one of them to the other type so 0 casted to string equals "0" which so they are the same, if it's "0" which is casted to number also casts to 0 so its the same as the other value, and so this comparison returns true.

In third case:

null=="0"

here's the same situation, both are different types so PHP cast one of them to the type of the other, but if you cast null to string the result is "null" which is not equal to "0", so that's the reason is not true that comparison.

like image 76
Nelson Avatar answered Dec 27 '22 18:12

Nelson