Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is -1 > null true in php

Tags:

php

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 ?

like image 225
Marco de Jongh Avatar asked May 01 '14 09:05

Marco de Jongh


People also ask

Is null true PHP?

It's language specific, but in PHP :Null means "nothing". The var has not been initialized. False means "not true in a boolean context". Used to explicitly show you are dealing with logical issues.

Does PHP empty check for null?

The empty() function returns true if the value of a variable evaluates to false . This could mean the empty string, NULL , the integer 0 , or an array with no elements. On the other hand, is_null() will return true only if the variable has the value NULL .

Is null and 0 same true or false?

0 is not equal to null and hence both are false as well. More generally speaking: Operators are defined for specific data types and if you pass a value of a different data type that value will be converted to the expected data type first. > and < are defined for strings and numbers but not for null .

Is null and 0 the same PHP?

PHP considers null is equal to zero.


1 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.)

like image 71
Qantas 94 Heavy Avatar answered Sep 30 '22 17:09

Qantas 94 Heavy