SyntaxStudy
Sign Up
PHP json_decode() in PHP
PHP Beginner 4 min read

json_decode() in PHP

json_decode()

json_decode() converts JSON to a PHP object or array. Pass true as the second argument to get an associative array instead of stdClass.

Example
<?php
$json = '{"name":"Alice","age":30,"tags":["admin"]}';

// Default: stdClass object
$obj = json_decode($json);
echo $obj->name; // "Alice"

// As associative array (recommended)
$arr = json_decode($json, true);
echo $arr["name"]; // "Alice"

// Error handling
$result = json_decode($badJson, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new InvalidArgumentException("Invalid JSON: " . json_last_error_msg());
}
Pro Tip

Always pass true as the second argument to json_decode() to get arrays — stdClass objects are harder to work with.