1

I've stumbled upon unusual PHP behaviour.

First of all let me say that it was pure interest and was never intended to be used in a production

$my_array = array(NAN => "one", INF => "two");

print_r($my_array);

The result is

Array
(
    [-2147483648] => one
    [0] => two
)

Can please anyone explain me how come

  • they do not generate warnings (especially INF casted to 0 that overrides other value with the same key if any)

  • why NAN casts to −9,223,372,036,854,775,808 on 64bit and -2,147,483,648 on 32bit machine (lowest long you can get)

  • INF silently becomes zero

I can see NAN and INF become those numbers if casted to int but would not it be more logical if NAN would cast 0 and INF would be maximum positive number?

Vladimir Hraban
  • 3,543
  • 4
  • 26
  • 46
  • "would not it be more logical if NAN would cast 0" - No, since NaN is not a number, it should not be cast as any specific value instead of any other one. These values are not meant to be treated as numbers anyway, and the doc states that they've no fixed value : http://php.net/manual/en/math.constants.php – Clément Malet Sep 03 '14 at 12:51
  • That seems to be system/version dependent as well – when I try your code as shown, I get an array that contains only _one_ element with index `-9223372036854775808` and value `two`, value `one` doesn’t even show up. – CBroe Sep 03 '14 at 13:11
  • @CBroe, could you please tell me what if you just echo (inf)NAN? Is is that your NaN just gets ignored or it is also casted to -9223372036854775808? – Vladimir Hraban Sep 03 '14 at 13:35
  • @ClémentMalet In this case a warning / exception should be generated and php should not allow to cast neither INF nor NAN – Vladimir Hraban Sep 03 '14 at 13:37
  • 1
    Yes, looks like NAN is also casted to -9223372036854775808, cause when I just leave the first key-value pair in your array, that’s what I get – same as for the second one on its own, so PHP overwrites the element here because it considers the key the same. (PHP version is 5.5.5 on a 64 bit linux machine.) – CBroe Sep 03 '14 at 15:07

1 Answers1

0

Floats are truncated to integers as stated in PHP manual and this answer Working with an array with periods in key values

The reason why the INF is converted to 0 is still strange to me.

Community
  • 1
  • 1
j123b567
  • 3,110
  • 1
  • 23
  • 32