Error "Cannot use object of stdClass as array" when working with JSON in PHP
Hello everyone! I'm a beginner in PHP and have been struggling with an error for hours that I just can't fix. I'm writing a script that receives data from an external API in JSON format. I use `json_decode()` to convert the response into an array, but when I try to access elements using square brackets, PHP throws a fatal error: "Cannot use object of type stdClass as array".
Here's my code:
```php
$json = '{"name": "Ivan", "age": 30, "city": "Moscow"}';
$data = json_decode($json);
echo $data['name']; // Error here!
```
I thought that `json_decode()` returns an array by default, but it turns out that's not the case. I tried reading the documentation, but there are many unfamiliar terms. Please advise how to properly access data after decoding JSON? Why does PHP complain? And how to make
No answers yet.
Log in to leave an answer
Blogs