Bug #77038 [Opn->Dup]: Object to Array conversion gives duplicate keys
| From: | nikic@php.net | Date: | Fri, 19 Oct 2018 08:26:48 +0000 |
| Subject: | Bug #77038 [Opn->Dup]: Object to Array conversion gives duplicate keys | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-217633@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=77038&edit=1
ID: 77038
Updated by: nikic@php.net
Reported by: jonathan at x6 dot nl
Summary: Object to Array conversion gives duplicate keys
-Status: Open
+Status: Duplicate
Type: Bug
Package: *General Issues
Operating System: CentOS Linux release 7.5.1804
PHP Version: 7.0.32
Block user comment: N
Private report: N
New Comment:
This has already been fixed in PHP 7.2, see https://wiki.php.net/rfc/convert_numeric_keys_in_object_array_casts.
Previous Comments:
------------------------------------------------------------------------
[2018-10-19 07:32:22] jonathan at x6 dot nl
Description:
------------
In the case if you have a stdClass with only numeric keys (for example, this is a decoded json
string). And convert it to array, it will change the keys to strings.
If you then add that same value as an integer into the array, it will be added to the array.
If you then do a json_encode, you get an invalid json string, because you have duplicate keys.
It seems somehow that when the object is converted to array, the types of values will be changed.
This seems like a bug, since in our particular example we tried to check if an ID was already in the
array (with doing isset($array[$id])). This example returned false because the ID was changed to a
string.
Test script:
---------------
<?php
// Create new stdClass with numeric attribute, stored as string.
$bla = new stdClass;
$bla->{"1012"} = "Value 1";
$bla->{1012} = "Value 2";
// Convert to array
$bla = (array) $bla;
if (!isset($bla[1012])) {
// ISSET fails, because it is now "1012" instead of 1012
var_dump($bla);
$bla[1012] = "Value 4";
}
var_dump($bla);
echo json_encode($bla);
Expected result:
----------------
The object needs to be correctly converted.
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=77038&edit=1