The comparison operator "==" in the confusion of PHP

In PHP,

null==0 0=="0" 

If you combine these two, you expect:

 null=="0" 

But this is not so.

Can anyone explain this to me?

+4
source share
3 answers

You should understand that since PHP is not strict when typing, it often distinguishes your variables from other types depending on the necessary comparison or operation. In the case of null == 0, it tells you that both zero and the integer 0 are considered false.

In the case of null == "0", it checks if the string "0" is empty, which it is not. Comparing the integer 0 with the strings of type "0" of the type "0" to int for comparison, in this case they are equal.

Hope this helps.

+1
source

In the first case:

 null==0 

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

In the second case:

 0=="0" 

here you are comparing two variables of different types, one is a digit and the other is a string, because you do not use === , PHP passed one of them to another type, therefore 0 , cast to a string is "0" , therefore they are the same if they " 0 " , which is added to the number, also adds to 0 , so its value matches another value, and therefore this comparison returns true.

In the third case:

 null=="0" 

here the same situation, both are different types, so PHP applies one of them to the type of the other, but if you pass null to a string, the result is "null" that is not equal to "0" , so the reason is not what a comparison.

+10
source

== checks equality

=== checks the type of equality AND (we also say that it is "identical")

Therefore, since PHP does not have a strong hint of type, it is automatically assigned to the most appropriate type.

null === 0 is false , while null == 0 true because 0 or '0' considered a null value, as well as false . An empty null == '' will also return true .

How does PHP work.

Best practice is to type check with the === operator (and its negative equivalent !== and use only the other in special cases).

+1
source

Source: https://habr.com/ru/post/1434799/


All Articles