php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #46758 casting object to array messes numeric indexes
Submitted: 2008-12-05 10:40 UTC Modified: 2008-12-30 20:39 UTC
From: markus dot kristo at esportnetwork dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.2.7 OS: *
Private report: No CVE-ID: None
 [2008-12-05 10:40 UTC] markus dot kristo at esportnetwork dot com
Description:
------------
json_encoding and json_decoding an array with string indices as numbers starting from anything else than zero will create an array that can't be used to fetch elements from. 

Note that this only happens when you cast the resulting object from json_decode to an array. 

Please look at the attached code example for more information about this bug.

Reproduce code:
---------------
<?php

$array = array("1" => "one"); // array("0" => "zero") works fine.

$foo = (array) json_decode(json_encode($array)); 
// $foo = json_decode(json_encode($array), true) works fine

var_dump($foo);
// array(1) {
//  ["1"]=>
//  string(3) "one"
// }

var_dump($foo["1"]); // Outputs PHP Notice and NULL expected "one"

?>

Expected result:
----------------
I expect the last var_dump to output "one"

Actual result:
--------------
The last var_dump outputs NULL and a PHP Notice "undefined index: 1" is shown

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-12-08 11:28 UTC] jani@php.net
This has nothing to do with JSON at all, same happens with this:

<?php

$a->{"1"} = "one";

$foo = (array) $a;

var_dump($foo);
var_dump($foo["1"]);

?>
 [2008-12-30 20:39 UTC] felipe@php.net
That is an known issue, it's documented:
http://docs.php.net/manual/en/language.types.array.php

Thanks.
 [2017-03-02 07:48 UTC] cweiske@php.net
The relevant section in the documentation:

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible [...]
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 28 22:01:28 2024 UTC