Underlying philosophy behind php type comparisons

前端 未结 7 1825
不思量自难忘°
不思量自难忘° 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:00

    For casting directly to a boolean this is how it works.

    • All string with a length > 0 are true
    • All non 0 numbers are true
    • All non-empty arrays are true
    • All objects are true

    Then these rules for comparing variables of the same type:

    1. Objects are equivalent if their properties are equal
    2. Arrays are equivalent if their keys and elements are equal
    3. Strings are equivalent if they would produce the same output
    4. Numbers are equivalent if they are mathematically equivalent
    5. Booleans are equivalent if they have the same value.

    For variable of different types the type that is higher on the above list is cast to the one that is lower then the comparison is made.

    === and !== operators don't cast prior to comparing but you should note objects are only === if they are the same instance.

    The really odd one is arrays, they are === if they have the same keys and values defined in the same order.

    $a = array("a"=>1, "b"=>2);
    $b = array("b"=>2, "a"=>1);
    
    $a == $b; // true
    $a === $b; // false
    

    and empty() is equivalent to !(bool)$var

    EXCEPTIONS

    • Casting an array to a string will trigger a notice and unhelpfully cast as the text Array
    • Casting an object without a __toString method to a string will get you a fatal error.
    • Objects will not implicitly cast to an array, so any time you compare an object to an array it will yield a false (UPDATE confirmed that this is true even if object implemtents the ArrayAccess interface)

提交回复
热议问题