I am using php’s json_decode to decode some json, but i’ve been getting a /var/log/apache/error_log:PHP Fatal error: Cannot use string offset as an array
$data = json_decode($this->body, true);
if (is_null($data))
{
throw new Exception(...);
}
...
$foo = $data['foo']['bar']; // this line causes the fatal error
...
Based on some research, the only way that can cause the error is if $data is a string. but since json_decode with $assoc = to true seems to guarantee null or an array, that should not be the case. Can anyone think of any way how that code could possibly cause an error?
Of course
json_decodecan return other types, and$assochas nothing to do with it.$assoc = trueonly means that objects (associative arrays) in the JSON will be decoded as PHP associative arrays, while the default is to decode them as PHP objects. It does not affect any other type of data in the JSON, so if your root JSON element is not an array, thejson_decodewill return non-array too.