Bug #70692 [Opn->Dup]: Undefined offset in array, but key is set
| From: | ajf@php.net | Date: | Sat, 19 Dec 2015 04:08:56 +0000 |
| Subject: | Bug #70692 [Opn->Dup]: Undefined offset in array, but key is set | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-198021@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=70692&edit=1
ID: 70692
Updated by: ajf@php.net
Reported by: havenard at hotmail dot com
Summary: Undefined offset in array, but key is set
-Status: Open
+Status: Duplicate
Type: Bug
Package: JSON related
Operating System: Windows
PHP Version: 5.6.14
Block user comment: N
Private report: N
New Comment:
Duplicate of bug #66173
Previous Comments:
------------------------------------------------------------------------
[2015-10-12 06:59:02] havenard at hotmail dot com
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
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=70692&edit=1