Bug #70925 [Com]: json_decode-d object become inacccessible after converting to array

From: Date: Tue, 17 Nov 2015 03:01:39 +0000
Subject: Bug #70925 [Com]: json_decode-d object become inacccessible after converting to array
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-197292@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=70925&edit=1 ID: 70925 Comment by: nhojohl at gmail dot com Reported by: speller at yandex dot ru Summary: json_decode-d object become inacccessible after converting to array Status: Open Type: Bug Package: Scripting Engine problem PHP Version: 5.6.15 Block user comment: N Private report: N New Comment: This is a known issue and was marked as "won't fix" long ago. It's in the official PHP documentation as well. http://www.php.net/manual/en/language.types.array.php#language.types.array.casting "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" The recommended solution is to use the second parameter of json_decode to have the son decoded as an array without the need to cast it. For more information see: https://bugs.php.net/bug.php?id=45959 Previous Comments: ------------------------------------------------------------------------ [2015-11-17 02:36:45] speller at yandex dot ru Description: ------------ Bug converting json_decoded-d object to array. First seen in PHP 5.4. Confirmed in PHP 5.6.15. See the test script. We have a simple array $a. Next we convert it to JSON and back. But after transcoding we can not access the array's values and get NULL or "Notice: Undefined offset: 1". If replace the line "$a = (array)json_decode(json_encode($a));" with "$a = (array)((object)$a);" everything is OK, converted array's values are accessible. The test script output is: array(2) { [1] => string(7) "value 1" [2] => string(7) "value 2" } string(7) "value 1" string(7) "value 1" array(2) { '1' => string(7) "value 1" '2' => string(7) "value 2" } NULL NULL Test script: --------------- <? error_reporting(0); $a = ['1' => 'value 1', '2' => 'value 2']; var_dump($a); var_dump($a[1]); var_dump($a['1']); $a = (array)json_decode(json_encode($a)); var_dump($a); var_dump($a[1]); var_dump($a['1']); ?> Expected result: ---------------- The values of the converted array must be accessible Actual result: -------------- NULL or Notice: Undefined offset: 1 ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=70925&edit=1

« previous php.bugs (#197292) next »