json_decode()
json_decode() — Decodes a JSON string.
Built-in function of PHP 8.5. The manual lists it as available in PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
Takes a JSON encoded string and converts it into a PHP value.
Signature
json_decode(string $json, ?bool $associative = null, int $depth = 512, int $flags = 0): mixed
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $json | string | The json string being decoded. |
| $associative | ?bool | When true, JSON objects will be returned as associative arrays; when false, JSON objects will be returned as objects. When null, JSON objects will be returned as associative arrays or objects depending on whether JSON_OBJECT_AS_ARRAY is set in the flags. |
| $depth | int | Maximum nesting depth of the structure being decoded. The value must be greater than 0, and less than or equal to 2147483647. |
| $flags | int | Bitmask of JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR. The behaviour of these constants is described on the JSON constants page. |
Return value
Returns the value encoded in json as an appropriate PHP type. Unquoted values true, false and null are returned as true, false and null respectively. null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting limit.
Example
A runnable snippet:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); var_dump(json_decode($json, true));
Output:
object(stdClass)#1 (5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) } array(5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) }
Changelog
| Version | Change |
|---|---|
| 7.3.0 | JSON_THROW_ON_ERROR flags was added. |
| 7.2.0 | associative is nullable now. |
| 7.2.0 | JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE flags were added. |
| 7.1.0 | An empty JSON key ("") can be encoded to the empty object property instead of using a key with value _empty_. |
See also
json_encode(), json_last_error(), json_last_error_msg()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page json_decode() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.