Question

I have recently stumbled upon a situation that seems to be a bug at best. Both null and false appear to be evaluated to lower but not equal to negative infinity when used in comparisons.

My current test case:

var_dump(
    PHP_OS,
    PHP_VERSION,
    null == 0,                        # true
    false == 0,                       # true
    INF==INF,                         # true
    (-1*INF) == (-1*INF),             # true
    (-1*INF) < (-1*INF),              # false!
    (-1*INF) > (-1*INF),              # false!
    'Insane In The Membrane',
    null == (-1*INF),                 # false!?
    false == (-1*INF),                # false!?
    null  < (-1*INF),                 # true!
    false < (-1*INF)                  # true!
);

This was run on various PHP Versions and on some windows machines that I had access to. All had the surprising same result.


Ignoring the first two debug dumps, The next 6 results are what you'd expect if you're a seasoned PHP developer. The first two are due to type juggling and the last 4, are due to PHP and math.


Now the last four are what's bugging me.

I'm uncertain if it is even valid in math to have something lower than negative infinity.

What's stranger still is the combination of the first two and the last two comparisons. Somehow the same type juggling algorithm makes this valid:

var_dump(
    'Insane In The Membrane (Redux)',
    (null  == 0) && (null  < (-1*INF)),     # true
    (false == 0) && (false < (-1*INF))      # true
);

If anyone can give any insight as to how these type casts are being evaluated so differently and why that would be greatly appreciated.


P.S. I have tried searching SO again and again and again, the PHP Manual and even the PHP bug tracker, all to no avail. I tried looking through the C source code to determine the bits and pieces that make this code work the way it does. Still no dice.

Was it helpful?

Solution

I just was looking at this yesterday. We'll venture to the PHP manual and look at the comparison operators page:

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

There is a great chart there that explains what happens when objects of different types are compared, and this is one of its columns:

bool or null    anything    Convert to bool, FALSE < TRUE

So, null is casted to false and any nonzero number is casted to true. Source And, as you can see, FALSE < TRUE. This is why you get supposedly insane behavior - As to why this might be the case, it may be because of C's similar behavior. (But C never lets you play this fast and loose with the typing system!)

OTHER TIPS

Maybe this will help:

http://gynvael.coldwind.pl/?id=492

It mostly covers the == operator but also has some info and pointers about how comparisons work in general.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top