php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #70692 Undefined offset in array, but key is set
Submitted: 2015-10-12 06:59 UTC Modified: 2015-12-19 04:08 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: havenard at hotmail dot com Assigned:
Status: Duplicate Package: JSON related
PHP Version: 5.6.14 OS: Windows
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: havenard at hotmail dot com
New email:
PHP Version: OS:

 

 [2015-10-12 06:59 UTC] 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

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-12-19 04:08 UTC] ajf@php.net
-Status: Open +Status: Duplicate
 [2015-12-19 04:08 UTC] ajf@php.net
Duplicate of bug #66173
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 21 15:01:30 2024 UTC