php.net |  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
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: jonathan at x6 dot nl
New email:
PHP Version: OS:

 

 [2018-10-19 07:32 UTC] 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.


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-10-19 08:26 UTC] nikic@php.net
-Status: Open +Status: Duplicate
 [2018-10-19 08:26 UTC] nikic@php.net
This has already been fixed in PHP 7.2, see https://wiki.php.net/rfc/convert_numeric_keys_in_object_array_casts.
 [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 https://3v4l.org/LLZeC

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-2018 The PHP Group
All rights reserved.
Last updated: Mon Nov 19 10:01:25 2018 UTC