Fix PHP Fatal error: Cannot use object of type stdClass as array

beginner🐘 PHP2026-04-03| PHP 7.2+, PHP 8.x, Linux (Ubuntu/CentOS), Docker (php-fpm)

Error Message

Fatal error: Cannot use object of type stdClass as array in /var/www/html/api.php on line 18
#php#json#stdClass#debugging#api

The Problem

It’s late, and you’re finally wrapping up an API integration. The external service sends back a valid JSON response, you call json_decode(), and then you try to grab a value. Suddenly, your script crashes.

$response = file_get_contents('https://api.example.com/user/1');
$data = json_decode($response);

echo $data['username']; // This triggers the Fatal Error

Instead of the username, you get a blunt error message: Fatal error: Cannot use object of type stdClass as array. Your code stops dead in its tracks.

Why this happens

By default, json_decode($json) returns an object of type stdClass. PHP won't let you use square brackets ($data['key']) on objects unless they implement the ArrayAccess interface. Since stdClass is just a generic, empty container, it only understands the arrow operator (->).

Think of it as trying to use a key on a door that only has a handle. The syntax doesn't match the structure.

The 1-Second Fix: Use the Boolean Flag

The fastest solution is to pass true as the second argument to json_decode(). This tells PHP to return an associative array instead of an object. Most developers prefer this because arrays are easier to manipulate in loops.

// Change this:
$data = json_decode($response);

// To this:
$data = json_decode($response, true);

// Now this works perfectly:
echo $data['username'];

Alternative: Stick with Object Syntax

Sometimes you might want to keep the data as an object, especially if other parts of your app expect that format. In this case, simply swap your square brackets for the arrow operator. It's cleaner and slightly faster in some PHP versions.

$data = json_decode($response);

// Access as an object property
echo $data->username; 

What if the JSON key has a hyphen, like user-id? You can't write $data->user-id because PHP thinks you're trying to subtract a constant. Use curly braces instead: $data->{'user-id'}.

Dealing with Deeply Nested Data

This error is most annoying with nested JSON. Imagine a structure like {"meta": {"status": 200}}. If you forget the true flag, $data['meta']['status'] fails at the very first bracket.

To see exactly what PHP is working with, run var_dump($data). If you see class stdClass, use arrows. If you see array, use brackets. It’s the quickest way to verify your data structure before writing more code.

Verification and Safety

Don't assume the API always returns valid data. A common mistake is trying to access an array on a null value because the JSON was malformed. Add a simple check to make your code production-ready:

$data = json_decode($response, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    throw new Exception("Invalid JSON received: " . json_last_error_msg());
}

if (isset($data['username'])) {
    echo "User: " . $data['username'];
}

Pro Tip: Inspecting Raw JSON

When I'm debugging weird API responses, I usually copy the raw string into a formatter to visualize the levels. I often use the JSON Formatter & Validator on ToolCraft. It runs entirely in your browser. This keeps sensitive production data or API keys from ever being sent to a third-party server.

Summary of the fix:

- **For Arrays:** Use `json_decode($json, true);` and `$data['key']`.
- **For Objects:** Use `json_decode($json);` and `$data->key`.
- **Debugging:** Check `json_last_error()` if the result is `null`.

Related Error Notes