When you work with APIs or external data sources in PHP, you often receive JSON. PHP can turn it into an object or an associative array with json_decode(). This guide shows both ways with a short example.
Key takeaways
- json_decode($json) returns an object by default.
- json_decode($json, true) returns an associative array.
- Always check for decoding errors.
- Loop through the result with foreach.
The code
Here is a sample JSON string with a resultList of items, each with an id and a displayName:
$data = '{"resultList":[{"id":1,"displayName":"Analytics","subLine":""},{"id":2,"displayName":"Automation","subLine":""}]}';
Decode it as an object and loop through the list to print each display name:
$b = json_decode($data);
foreach ($b->resultList as $item) {
echo $item->displayName . "<br />";
}
Convert to an array instead
Pass true as the second argument to get an associative array:
$arr = json_decode($data, true);
foreach ($arr['resultList'] as $item) {
echo $item['displayName'] . "<br />";
}
How it works
- $data holds the raw JSON string.
- json_decode($data) converts the string into a PHP object, or into an array when you pass true.
- foreach walks through every entry in resultList.
- echo prints the displayName of each entry.
Check for errors
If the JSON is invalid, json_decode() returns null. Check json_last_error() so you do not work with empty data:
$arr = json_decode($data, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "Invalid JSON: " . json_last_error_msg();
}
Building an API integration? Our web development team can help.
Frequently asked questions
What is the difference between an object and an array result?
With an object you read values as $b->name. With an associative array you read $arr['name']. Pick the style that suits your code.
Why does json_decode return null?
The JSON is invalid or too deeply nested. Check json_last_error_msg() for the reason.



