Underlying philosophy behind php type comparisons

前端 未结 7 1927
不思量自难忘°
不思量自难忘° 2021-02-10 00:38

So there\'s this page on the php site which shows the result of comparing different values:

http://php.net/manual/en/types.comparisons.php

This is a helpful refe

7条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-10 01:09

    For strict === comparision, the logic is easy: each value entity is equal only to itself, so TRUE === TRUE, "1" === "1", but "1" !== 1 etc.

    When it comes to == comparision, unfortunately there is no rule of thumb nor a clear logic. This is probably because the various forms of the operator were implemented by different programmers, without a central design decision. The best I can do is providing you with this graph to print and stick over the monitor:

    PHP equality graph

    The key of the grap is: A == B will be TRUE if and only if A and B are of two types directly connected by a line in the graph above. For instance, array() == NULL is TRUE because array() and NULL are directly connected, while array() == 0 is FALSE because there is no line connecting the two.

    Lines marked in red are the tricky (non obvious) equalities.

    I've omitted that each entity will be equal to itself (e.g. "1" == "1" etc.) but that should be easy to remember.

    As a final note, I'd like to explain why "php" == 0 is TRUE (non empty, non number string is equal to 0): because PHP casts "php" to number before comparision and, since it's not a number, it defaults to 0 and makes the test TRUE.

    Fun fact: there is no partition in this relation! If ever a transitive closure was allowed, you could easily say that True is False and False is True, destroying millennia of philosphy in four easy PHP statements :D

提交回复
热议问题