Undefined offset while accessing array element which exists

后端 未结 7 1293
日久生厌
日久生厌 2020-12-15 04:03

I have an array and PHP and when I print it out I can see the values I need to access, but when I try accessing them by their key I am getting a PHP Notice. I printed the ar

7条回答
  •  天涯浪人
    2020-12-15 04:11

    See this section on converting an object to an array in the PHP Manual:

    The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name.

    When converting to an array from an object in PHP, integer array keys are stored internally as strings. When you access array elements in PHP or use an array normally, keys that contain valid integers will be converted to integers automatically. An integer stored internally as a string is an inaccessible key.

    Note the difference:

    $x = (array)json_decode('{"207":"test"}');
    var_dump(key($x));  // string(3) "207"
    
    var_dump($x);
    // array(1) {
    //   ["207"]=>
    //   string(4) "test"
    // }
    
    
    $y['207'] = 'test';
    var_dump(key($y));  // int(207)
    
    var_dump($y);
    // array(1) {
    //   [207]=>
    //   string(4) "test"
    // }
    

    print_r on both those arrays gives identical output, but with var_dump you can see the differences.

    Here is some code that reproduces your exact problem:

    $output = (array)json_decode('{"207":"sdf","210":"sdf"}');
    
    print_r($output);
    echo $output[207];
    echo $output["207"];
    

    And the simple fix is to pass in true to json_decode for the optional assoc argument, to specify that you want an array not an object:

    $output = json_decode('{"207":"sdf","210":"sdf"}', true);
    
    print_r($output);
    echo $output[207];
    echo $output["207"];
    

提交回复
热议问题