Undefined offset while accessing array element which exists

Kevin Rave picture Kevin Rave · Jun 18, 2012 · Viewed 15.6k times · Source

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 array with print_r:

Array
(
    [207] => sdf
    [210] => sdf
)

When I try to access the array using the index I get an undefined offset notice. Here is my code:

print_r($output); 
echo $output[207];   // Undefined Offset
echo $output["207"]; // Undefined Offset

The $output array is the result of a call to array_diff_key and is input originally as JSON through an HTTP POST request.

array_keys gives me the following:

Array
(
   [0] => 207
   [1] => 210
)

In response to the comments:

var_dump(key($output)); outputs:

   string(3) "207"

var_dump(isset($output[key($output)])); outputs:

   bool(false)

Answer

Paul picture Paul · Jun 18, 2012

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