Search code examples
phpstringperlcomparisonsemantics

PHP & Perl behavior when testing "0", "-0", "0.0", "00",


I came across this interesting behavior when PHP/Perl tests a value

print "0"   ? "Yes" : "No"; // => No
print "00"  ? "Yes" : "No"; // => Yes
print "0.0" ? "Yes" : "No"; // => Yes
print "-0"  ? "Yes" : "No"; // => Yes
print "+0"  ? "Yes" : "No"; // => Yes
print "0 "  ? "Yes" : "No"; // => Yes

So it seems the numeric value within the string doesn't really matter, but there is a specific case for the string "0".

What surprised me the most is that Perl does behave the same.
Why is there a specific case for the string being exactly "0"?


Solution

  • You are using the ternary operator which checks for the truthiness of the expression before the ?. The truthiness of values is described in the Booleans section:

    When converting to bool, the following values are considered false:

    • the boolean false itself
    • the integer 0 (zero)
    • the floats 0.0 and -0.0 (zero)
    • the empty string, and the string "0"
    • an array with zero elements
    • the special type NULL (including unset variables)
    • SimpleXML objects created from attributeless empty elements, i.e. elements which have neither children nor attributes.

    Every other value is considered true (including any resource and NAN).

    So yes, the string "0" is treated as a special case.


    Perl's Truth and Falsehood behave like somewhat like PHP.