Home » Php » Why is -1 > null true in php

Why is -1 > null true in php

Posted by: admin April 23, 2020 Leave a comment

Questions:

In PHP (5.3.14), the following code returns true:

-1 > null

The exact same code in JavaScript returns false. What is the reason behind this ?

How to&Answers:

PHP converts both sides to booleans when there is a null on one side.

The PHP manual section on Comparison Operators states that where the type of operand 1 is “bool or null”, or vice versa, it “converts both sides to bool, FALSE < TRUE“.

Any number that has a non-zero value is considered to be truthy, though this may not be intuitive.


In JavaScript, the comparison is defined differently so they are compared numerically (null -> 0).

ECMA-262, the official JavaScript specification, states that:

3. If it is not the case that both Type(px) is String and Type(py) is String, then

a. Let nx be the result of calling ToNumber(px). Because px and py are primitive values evaluation order is not important.
b. Let ny be the result of calling ToNumber(py).

PHP is well-known to be have a rather inconsistent type coercion system — PHP: a fractal of bad design highlights a few other issues that PHP suffers from. (Dare I say, I personally think it’s worse than JavaScript, a language also known for sneaky type coercions.)