|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #51635 casting json objects to array
Submitted: 2010-04-22 15:49 UTC Modified: 2010-04-22 17:28 UTC
From: joel dot gaehwiler at bluewin dot ch Assigned:
Status: Not a bug Package: JSON related
PHP Version: 5.2.13 OS: Windows
Private report: No CVE-ID: None
 [2010-04-22 15:49 UTC] joel dot gaehwiler at bluewin dot ch
We use this array:
array(2) { [1]=>  int(100) [2]=>  int(200) }

When a array will be encoded into a json string, php converts integer indexes t o strings:
string(17) "{"1":100,"2":200}"

When php decodes the json string back, it will be an object:
object(stdClass)#1 (2) { ["1"]=>  int(100) ["2"]=>  int(200) }

To avoid the problem that you not can acces integer indexes of a object you must cast the object to an array:
array(2) { ["1"]=>  int(100) ["2"]=>  int(200) }

Now the indexes become strings instead of integers, which you cannot access:
$arr2[1] = NULL

The json_decode function should convert indexes back to integer, if they are a string number, like php always does when you create an array.

Test script:
$arr = array(1=>100,2=>200,"1"=>100,"2"=>200);
$json = json_encode($arr);
$arr2 = (array)json_decode($json);

Expected result:
array(4) {

Actual result:
array(4) {


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2010-04-22 17:28 UTC]
-Status: Open +Status: Bogus
 [2010-04-22 17:28 UTC]
This is expected, javaScript arrays are zero-indexed so your PHP array can't be represented as a javaScript array and has to be converted to an object. When converting an object back PHP defaults to objects. But you can use the second param for json_decode().

For the inaccessible keys which are the result then there's another report already. So that part is duplicate.
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Sun Apr 18 12:01:24 2021 UTC