Question

How to Fix "Cannot Use Object of Type stdClass as Array" in PHP json_decode()

phpjson

Question

I am using json_decode() in PHP. The JSON appears to decode correctly because I can inspect the result with print_r(). However, when I try to access a value like this:

$result['context'];

I get the following error:

Fatal error: Cannot use object of type stdClass as array

$result contains the value returned by json_decode(). How should I correctly read values from it, and why does this error happen?

Short Answer

By the end of this page, you will understand why json_decode() often returns a stdClass object in PHP, why array syntax like $result['context'] fails in that case, and how to fix it by either using object property access or decoding JSON as an associative array.

Concept

In PHP, json_decode() converts a JSON string into a PHP value. The important detail is that it can return different types depending on how you call it.

By default, JSON objects become PHP objects of type stdClass.

That means this JSON:

{"context":"hello","count":3}

usually becomes something like this in PHP:

$result = json_decode($json);

Now $result is an object, not an array. So you must access values using object syntax:

$result->context;

If you try this instead:

$result['context'];

PHP throws this error because bracket syntax is for arrays, not objects.

If you want json_decode() to return an associative array instead of an object, pass true as the second argument:

$result = json_decode($json, true);

Then this works:

$result['context'];

This matters in real programming because JSON is used everywhere: APIs, config files, AJAX responses, logs, and stored data. If you do not know whether your decoded data is an object or an array, you will quickly run into type-related bugs.

Mental Model

Think of JSON data as a package that PHP can unpack in two different shapes:

  • Object shape: like a person with named properties
    • Access with ->
  • Array shape: like a box with named slots
    • Access with ['key']

If PHP gives you a person, you cannot open it like a box.

So:

  • stdClass object → use ->
  • associative array → use ['key']

The error happens because you are treating one shape as if it were the other.

Take Quiz

Syntax and Examples

The core syntax of json_decode() is:

json_decode(string $json, ?bool $associative = null)

Example 1: Default behavior returns an object

<?php
$json = '{"context":"hello","count":3}';
$result = json_decode($json);

echo $result->context; // hello
echo $result->count;   // 3

Here, $result is a stdClass object.

Example 2: Return an associative array

<?php
$json = '{"context":"hello","count":3}';
$result = json_decode($json, true);

echo $result['context']; // hello
echo $result['count'];   // 3

Here, $result is an associative array.

Example 3: Nested JSON

<?php
$json = '{"user":{"name":"Dail","age":25}}';

$obj = json_decode($json);
echo $obj->user->name; // Dail

$arr = json_decode($json, true);
echo $arr['user']['name']; // Dail

The access style must match the decoded type at every level.

Example 4: Check for JSON errors

<?php
$json = '{"context":"hello"}';
$result = json_decode($json, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo 'Invalid JSON: ' . json_last_error_msg();
} else {
    echo $result['context'];
}

This helps when decoding fails and returns null.

Step by Step Execution

Consider this code:

<?php
$json = '{"context":"hello"}';
$result = json_decode($json);
echo $result->context;

Step by step:

  1. $json stores the JSON string:

    '{"context":"hello"}'
    
  2. json_decode($json) parses the JSON.

  3. Because no second argument is provided, PHP converts the JSON object into a stdClass object.

  4. $result now behaves like this conceptually:

    $result = (object) ['context' => 'hello'];
    
  5. echo $result->context; reads the context property from the object.

  6. Output:

    hello
    

Now look at the broken version:

<?php
$json = '{"context":"hello"}';
$result = json_decode($json);
echo $result['context'];

What happens:

  1. $result is still a stdClass object.
  2. $result['context'] tries to use array syntax.
  3. PHP stops with:
    Fatal error: Cannot use object of type stdClass as array
    

Fix it in one of two ways:

Option 1: Keep object output

$result = json_decode($json);
echo $result->context;

Option 2: Decode as array

$result = json_decode($json, true);
echo $result['context'];

Real World Use Cases

This concept appears often in real PHP applications.

API responses

When calling an external API:

$response = file_get_contents('https://api.example.com/user');
$data = json_decode($response, true);
echo $data['name'];

If you forget the true, you must use object syntax instead.

AJAX requests

A frontend app may send JSON to PHP, and PHP may decode it:

$input = file_get_contents('php://input');
$data = json_decode($input, true);

Developers often prefer arrays here because they work well with validation and form-like processing.

Configuration files

JSON config files can be loaded into PHP:

$config = json_decode(file_get_contents('config.json'), true);
$host = $config['database']['host'];

Logging and data transformation

When reading JSON logs or imported data, developers choose arrays or objects depending on how they want to process nested values.

Database-backed APIs

A PHP backend may decode request JSON, validate it, and then save values to a database. Consistent use of arrays or objects makes that process easier and less error-prone.

Take Quiz

Real Codebase Usage

In real projects, developers usually pick one style and stay consistent.

Common pattern: decode to arrays for input data

Many codebases use:

$data = json_decode($json, true);

Why?

  • Easier to validate with array-based helpers
  • Works naturally with isset(), array_key_exists(), and loops
  • Familiar for request payload handling

Example:

$data = json_decode($requestBody, true);

if (!isset($data['email'])) {
    throw new InvalidArgumentException('Email is required');
}

Common pattern: use objects for structured responses

Some developers prefer objects when data feels like an entity:

$user = json_decode($json);

if (!isset($user->email)) {
    throw new InvalidArgumentException('Email is required');
}

Guard clauses

Always validate before reading values:

$data = json_decode($json, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException(json_last_error_msg());
}

if (!isset($data['context'])) {
    throw new RuntimeException('Missing context');
}

Error handling

In modern PHP, developers often use exceptions:

$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);

This avoids silently getting null on invalid JSON.

Consistency matters

The biggest real-codebase lesson is this:

  • Do not mix object access and array access randomly.
  • Decide whether your decoded JSON should be an object or an associative array.
  • Use that style consistently across the file or project.

Common Mistakes

1. Using array syntax on an object

Broken code:

$result = json_decode($json);
echo $result['context'];

Why it fails:

  • json_decode($json) returns a stdClass object by default.
  • Objects use ->, not [].

Fix:

echo $result->context;

2. Using object syntax on an associative array

Broken code:

$result = json_decode($json, true);
echo $result->context;

Fix:

echo $result['context'];

3. Mixing styles in nested data

Broken code:

$result = json_decode($json, true);
echo $result->user['name'];

If decoded as array, use array syntax all the way:

echo $result['user']['name'];

4. Forgetting to check for invalid JSON

Broken code:

$result = json_decode($json, true);
echo $result['context'];

If $json is invalid, $result may be null.

Safer version:

$result = json_decode($json, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_last_error_msg();
}

5. Assuming print_r() output means array

Beginners often see structured output from print_r() and assume it is an array. But print_r() can display both arrays and objects.

Check the type explicitly:

var_dump($result);

6. Accessing missing keys or properties

Even if the type is correct, the field may not exist.

For arrays:

if (isset($result['context'])) {
    echo $result['context'];
}

For objects:

if (isset($result->context)) {
    echo $result->context;
}

Comparisons

SituationResult TypeAccess SyntaxExample
json_decode($json)stdClass object->$result->context
json_decode($json, true)associative array[]$result['context']

Object vs associative array in PHP

FeatureObject (stdClass)Associative Array
Access style$obj->name$arr['name']
Common with json_decode() defaultYesNo
Easy to use with array functionsNoYes
Good for entity-like dataYesSometimes
Good for validation and input handlingSometimesYes

Which should you choose?

  • Choose object output if you prefer property-style access.
  • Choose associative arrays if you want compatibility with array functions and common input-handling patterns.
  • In beginner code, arrays are often easier to work with consistently.

print_r() vs var_dump()

FunctionBest for
print_r()Quick readable inspection
var_dump()Exact type and structure

If you are unsure whether something is an object or array, var_dump() is more helpful.

Take Quiz

Cheat Sheet

Quick rules

  • json_decode($json) → returns object (stdClass) by default
  • json_decode($json, true) → returns associative array
  • Object access → ->
  • Array access → ['key']

Common patterns

$result = json_decode($json);
echo $result->context;
$result = json_decode($json, true);
echo $result['context'];

Nested access

Object:

$result->user->name;

Array:

$result['user']['name'];

Error checking

$result = json_decode($json, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_last_error_msg();
}

Safer modern version

$result = json_decode($json, true, 512, JSON_THROW_ON_ERROR);

Debugging tip

var_dump($result);

Use this to confirm whether you have an object, array, or null.

FAQ

Why does json_decode() return stdClass instead of an array?

By default, PHP converts JSON objects into stdClass objects. Pass true as the second argument if you want an associative array.

How do I access values from a stdClass object in PHP?

Use object property syntax:

$result->context;

How do I make json_decode() return an array?

Use:

$result = json_decode($json, true);

Then access values with bracket syntax.

Why does print_r() show the data but access still fails?

Because print_r() can display both arrays and objects. Seeing structure does not mean it is an array.

What is the difference between -> and [] in PHP?

-> is used for object properties. [] is used for array elements.

What happens if the JSON is invalid?

json_decode() usually returns null. You should check json_last_error() or use JSON_THROW_ON_ERROR.

Should I use objects or arrays after decoding JSON?

Either is fine, but be consistent. Arrays are often easier for validation and data processing in PHP.

Can nested JSON contain both arrays and objects?

Yes. JSON arrays become PHP arrays, while JSON objects become either stdClass objects or associative arrays depending on how you decode them.

Take Quiz

Mini Project

Description

Build a small PHP script that reads a JSON string representing a user profile and prints selected fields. This demonstrates the difference between decoding JSON as an object and as an associative array, and helps you practice the correct access syntax for each approach.

Goal

Decode JSON safely and display nested values correctly using either object syntax or array syntax.

Requirements

  1. Create a JSON string with a user name, email, and nested address data.
  2. Decode the JSON once as an object and once as an associative array.
  3. Print the same values from both decoded results.
  4. Include a check for invalid JSON before using the decoded data.
Take Quiz

Keep learning

Related questions

View more