3

How come null which is a predefined value in PHP equal to 0 and less than -1 at the same time? Refer to code below:

<?php
var_dump(null == 0); // evaluates to true
var_dump(null < -1); // this also evaluates to true
?>
Prabhas Gupte
  • 68
  • 2
  • 10
  • What is your use case for this? – Darren Nov 30 '15 at 05:54
  • I encountered `null` value for some variable while debugging a numeric comparison code block. It compares the same variable at two places with different conditions: `if ($var == 0) { .. some code .. } ... if ($var < -1) { .. some other code ..}` Where, developer expected control to enter only one of these two blocks, but ended up executing both. And, `null` is a valid value for that variable. – Prabhas Gupte Nov 30 '15 at 05:59
  • You can solve the first one by using a value & type comparison - `var_dump(null === 0); // returns false`. – Darren Nov 30 '15 at 06:01
  • Yes @Darren, that's what I did. My question is, when using `==` operator, why the same predefined value evaluates to `true` for such a not-possible-mathematically comparison? Isn't that a constant and supposed to evaluate to true for only and only one value? – Prabhas Gupte Nov 30 '15 at 06:03
  • Convert it to an `int` before you do your comparisons then -> `var_dump( (int) null == 0 );` **and** `var_dump( (int) null < -1 );` - only 1 will return true. – Darren Nov 30 '15 at 06:06
  • Yeah, that fixes the problem in code. But the question is really about inconsistent comparison in PHP (and not about how to fix it in code). – Prabhas Gupte Nov 30 '15 at 06:12
  • 1
    [The 3 different equals](http://stackoverflow.com/questions/2063480/the-3-different-equals) – Narendrasingh Sisodia Nov 30 '15 at 06:14

1 Answers1

5

it not the value of null which is giving you the results its the dynamic conversion happing during comparision

For the php manual

For various types, comparison is done according to the following table (in order).

http://php.net/manual/en/language.operators.comparison.php

enter image description here

You can see that if Operand 1 is bool or null and Operand 2 is anything than convert the side to bool applies, and also 0 is false in php, also in PHP treats null ,false, 0, and the empty string as equal. so

var_dump(null == 0);

is like var_dump(false == false); which evaluates to true

and var_dump(null < -1) is like var_dump(false < true) which is again true

hence you are getting these results

Dinkar Thakur
  • 3,025
  • 5
  • 23
  • 35