Bug #80701 [Opn]: NaN equals NaN in arrays, if two arrays have the same identity
| From: | cmb@php.net | Date: | Fri, 12 Feb 2021 16:04:23 +0000 |
| Subject: | Bug #80701 [Opn]: NaN equals NaN in arrays, if two arrays have the same identity | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-232097@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=80701&edit=1
ID: 80701
Updated by: cmb@php.net
Reported by: riikka dot kalliomaki at gmail dot com
Summary: NaN equals NaN in arrays, if two arrays have the
same identity
Status: Open
Type: Bug
Package: Arrays related
PHP Version: 8.0.1
Block user comment: N
Private report: N
New Comment:
Interesting edge case! The equality operator has the same issue.
Previous Comments:
------------------------------------------------------------------------
[2021-02-03 09:47:14] riikka dot kalliomaki at gmail dot com
Description:
------------
TL;DR; "$a = $b = [NAN]; [NAN] !== [NAN] && $a === $b".
PHP arrays don't officially have an identity. However, for optimization PHP uses copy on write
for arrays so two arrays can have the same "identity" when, for example, an array is
assigned to another variable.
For optimization, when using the strict comparison operator "===", PHP checks if the
identity of two arrays is same to quickly return true in those cases. I mean, one would expect that
two arrays that point to the same thing would be strictly equal.
However, this assumption is not true for NaN, i.e. [NAN] !== [NAN]. But, if you first assign the
[NAN] to a variable, it can equal itself, if two arrays have the same identity.
Based on https://3v4l.org/gHjG0, this seems have been
introduced in 5.3.15 / 5.4.5
I would consider this behavior to be a bug, but I'm not sure whether it is worth fixing since
that could have non negligible performance impact. I did not run into this bug in actual code and
simply realized it through personal musing. Thus, at least I don't personally consider fixing
it important.
Test script:
---------------
<?php
$NaN = sqrt(-1);
var_dump($NaN === $NaN);
var_dump(array($NaN) === array($NaN));
$a = array($NaN);
$b = $a;
var_dump($a === $b);
reset($b);
var_dump($a === $b);
Expected result:
----------------
bool(false)
bool(false)
bool(false)
bool(false)
Actual result:
--------------
bool(false)
bool(false)
bool(true)
bool(false)
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=80701&edit=1