PHP json_decode() Function

Quick summary: The PHP json_decode() function decodes a JSON string into a PHP variable.

PHP json_decode() Syntax

json_decode(string $json, bool $associative = false, int $depth = 512, int $flags = 0): mixed
PHP

PHP json_decode() Basic examples

$json = '{"a":1}';
var_dump(json_decode($json, true));
PHP
Output:
array(1) { ["a"]=> int(1) }

Decodes JSON into an associative array.

PHP json_decode() Real-world usage

$json = '{"status":"ok"}';
$data = json_decode($json);
echo $data->status;
PHP
Output:
ok

Accesses decoded JSON as an object.

PHP json_decode() Edge cases

var_dump(json_decode('invalid json'));
PHP
Output:
NULL

Invalid JSON returns null.

PHP json_decode() Common mistakes

Forgetting the associative flag

json_decode returns objects by default.

Incorrect
json_decode($json)['a'];
Correct
json_decode($json, true)['a'];

Pass true to get an associative array.

PHP json_decode() Frequently Asked Questions

What does json_decode() do in PHP?

json_decode() converts a JSON string into a PHP variable.

What is the syntax of json_decode()?

json_decode(string $json, bool $assoc = false, int $depth = 512, int $flags = 0): mixed

How to get an array instead of object?

Set the second parameter to true to return associative arrays.

Why does json_decode() return null?

Invalid JSON or decoding error; check json_last_error().

Is json_decode() safe for user input?

Yes, but always validate and sanitize input.

What is depth parameter?

It limits recursion depth for nested JSON structures.

Difference between assoc true and false?

true returns arrays, false returns objects.

Does json_decode() handle UTF-8?

Yes, input must be valid UTF-8.

Performance of json_decode()?

Fast and optimized for JSON parsing.

Can json_decode() throw exceptions?

Yes, with JSON_THROW_ON_ERROR flag.

Common mistake with json_decode()?

Forgetting assoc=true when expecting arrays.

Alternative to json_decode()?

Manual parsing is not recommended.

PHP json_decode() Related PHP Functions