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 as the second argument:
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
->
- Access with
- Array shape: like a box with named slots
- Access with
['key']
- Access with
If PHP gives you a person, you cannot open it like a box.
So:
stdClassobject → use->- associative array → use
['key']
The error happens because you are treating one shape as if it were the other.
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'];
[];
Step by Step Execution
Consider this code:
<?php
$json = '{"context":"hello"}';
$result = json_decode($json);
echo $result->context;
Step by step:
-
$jsonstores the JSON string:'{"context":"hello"}' -
json_decode($json)parses the JSON. -
Because no second argument is provided, PHP converts the JSON object into a
stdClassobject. -
$resultnow behaves like this conceptually:$result = (object) ['context' => 'hello']; -
echo $result->context;reads thecontextproperty from the object. -
Output:
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'), );
= [][];
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 (!(->email)) {
();
}
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 astdClassobject 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
Comparisons
| Situation | Result Type | Access Syntax | Example |
|---|---|---|---|
json_decode($json) | stdClass object | -> | $result->context |
json_decode($json, true) | associative array | [] | $result['context'] |
Object vs associative array in PHP
| Feature | Object (stdClass) | Associative Array |
|---|---|---|
| Access style |
Cheat Sheet
Quick rules
json_decode($json)→ returns object (stdClass) by defaultjson_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
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.
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
- Create a JSON string with a user name, email, and nested address data.
- Decode the JSON once as an object and once as an associative array.
- Print the same values from both decoded results.
- Include a check for invalid JSON before using the decoded data.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.