Undefined offset while accessing array element which exists Undefined offset while accessing array element which exists arrays arrays

Undefined offset while accessing array element which exists


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"];


The problem arises when casting to array an object that has string keys that are valid integers.

If you have this object:

object(stdClass)#1 (2) {  ["207"]=>  string(3) "sdf"  ["210"]=>  string(3) "sdf"}

and you cast it with

$array = (array)$object

you get this array

array(2) {  ["207"]=>  string(3) "sdf"  ["210"]=>  string(3) "sdf"}

which has keys that can only be accessed by looping through them, since a direct access like $array["207"] will always be converted to $array[207], which does not exist.

Since you are getting an object like the one above from json_decode() applied to a string like

$json = '{"207":"sdf", "210":"sdf"}'

The best solution would be to avoid numeric keys in the first place. These are probably better modelled as numeric properties of an array of objects:

$json = '[{"numAttr":207, "strAttr":"sdf"}, {"numAttr":210, "strAttr":"sdf"}]'

This data structure has several advantages over the present one:

  1. it better reflects the original data, as a collection of objectswhich have a numeric property
  2. it is readily extensible with other properties
  3. it is more portable across different systems(as you see, your current data structure is causing issues in PHP, but if youshould happen to use another language you may easily encountersimilar issues).

If a property → object map is needed, it can be quickly obtained, e.g., like this:

function getNumAttr($obj) { return $obj->numAttr; } // for backward compatibility$arr = json_decode($json); // where $json = '[{"numAttr":...$map = array_combine(array_map('getNumAttr', $arr), $arr);

The other solution would be to do as ascii-lime suggested: force json_decode() to output associative arrays instead of objects, by setting its second parameter to true:

$map = json_decode($json, true);

For your input data this produces directly

array(2) {  [207]=>  string(3) "sdf"  [210]=>  string(3) "sdf"}

Note that the keys of the array are now integers instead of strings.

I would consider changing the JSON data structure a much cleaner solution, though, although I understand that it might not be possible to do so.


I've just found this bug which causes array elements to be inaccessible sometimes in PHP when the array is created by a call to unserialize.

Create a test PHP file containing (or run from the command line) the following script:

<?php $a = unserialize('a:2:{s:2:"10";i:1;s:2:"01";i:2;}'); print $a['10']."\n";$a['10'] = 3; $a['01'] = 4; print_r($a);foreach ($a as $k => $v) {   print 'KEY: ';   var_dump($k);   print 'VAL: ';   var_dump($v);   print "\n"; }

If you get errors you have a version of PHP with this bug in it and I recommend upgrading to PHP 5.3