|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2015-12-19 04:08 UTC] ajf@php.net
-Status: Open
+Status: Duplicate
[2015-12-19 04:08 UTC] ajf@php.net
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Nov 05 05:00:01 2025 UTC |
Description: ------------ When converting a stdClass object instanced by json_decode() to array, the array is aparently fine with keys properly set as seen with print_r(), but they do not work. Trying to fetch an element will result in Notice: Undefined offset. Test script: --------------- <?php $data = [ 123 => (object)['name' => 'Example'] ]; print_r($data); // for reference, this shows the structure of the array $data echo $data[123]->name; // working as intented $data = json_encode($data); // serialize $data to {"123":{"name":"Example"}} echo "\n\n\n"; $data = json_decode($data); // unserialize json $data = (array)$data; // even though it was originally an array, $data is an object because JavaScript does not support non-contiguous arrays, so we have to explicitly convert to array print_r($data); // this shows the structure of the array $data looks just like it was before, all should be fine, but then... echo $data[123]->name; // BOOM! Notice: Undefined offset: 123 Expected result: ---------------- Array ( [123] => stdClass Object ( [name] => Example ) ) Example Array ( [123] => stdClass Object ( [name] => Example ) ) Example Actual result: -------------- Array ( [123] => stdClass Object ( [name] => Example ) ) Example Array ( [123] => stdClass Object ( [name] => Example ) ) PHP Notice: Undefined offset: 123 in test_script.php on line 19