Home >Backend Development >PHP Tutorial >Why Does json_decode() Throw \'Cannot use object of type stdClass as array\'?
Error "Cannot use object of type stdClass as array": A Json Decoding Conundrum
When working with JSON data using the json_decode() function, you may encounter an enigmatic error that reads: "Cannot use object of type stdClass as array". This error stems from the fact that json_decode() by default returns an object instead of an array, even though the JSON data you're decoding may be structured as an array.
To rectify this issue and enable access to array elements, you can leverage the second parameter of the json_decode() function. By setting this parameter to true, you instruct the function to return an array rather than an object.
For example, consider the following code:
$data = '{"context": "some value"}'; $result = json_decode($data);
In this scenario, $result would be an object, and attempting to access its "context" property as an array, e.g., $result['context'], would trigger the aforementioned error.
To resolve the error and read array values, modify the code as follows:
$result = json_decode($data, true);
By passing true as the second argument, json_decode() will create an array instead, and you'll be able to access its "context" element as expected:
$context = $result['context'];
The above is the detailed content of Why Does json_decode() Throw \'Cannot use object of type stdClass as array\'?. For more information, please follow other related articles on the PHP Chinese website!