|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #77038 Object to Array conversion gives duplicate keys
Submitted: 2018-10-19 07:32 UTC Modified: 2018-10-19 08:26 UTC
From: jonathan at x6 dot nl Assigned:
Status: Duplicate Package: *General Issues
PHP Version: 7.0.32 OS: CentOS Linux release 7.5.1804
Private report: No CVE-ID: None
 [2018-10-19 07:32 UTC] jonathan at x6 dot nl
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:
// 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
	$bla[1012] = "Value 4";

echo json_encode($bla);

Expected result:
The object needs to be correctly converted.


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2018-10-19 08:26 UTC]
-Status: Open +Status: Duplicate
 [2018-10-19 08:26 UTC]
This has already been fixed in PHP 7.2, see
 [2018-10-19 08:28 UTC] paul dot crovella at gmail dot com
7.0 is not actively supported, 7.1's active support is scheduled to end in just over a month, and 7.2 treats your sample code as you expect

Side note here:

> you get an invalid json string, because you have duplicate keys

Duplicate keys are valid in json. They're not recommended, but they are valid.
PHP Copyright © 2001-2022 The PHP Group
All rights reserved.
Last updated: Mon Aug 15 12:05:44 2022 UTC