How to Use json_decode in PHP: Syntax and Examples
Use
json_decode in PHP to convert a JSON string into a PHP variable like an object or array. Pass the JSON string as the first argument and optionally set the second argument to true to get an associative array instead of an object.Syntax
The json_decode function converts a JSON string into a PHP variable. It takes these parameters:
- string $json: The JSON string to decode.
- bool $assoc (optional): When
true, returns an associative array; whenfalseor omitted, returns an object. - int $depth (optional): Maximum depth to decode (default is 512).
- int $flags (optional): Bitmask of JSON decode options.
php
mixed json_decode(string $json, bool $assoc = false, int $depth = 512, int $flags = 0);
Example
This example shows how to decode a JSON string into a PHP object and an associative array.
php
<?php $jsonString = '{"name":"Alice","age":25,"city":"Paris"}'; // Decode as object (default) $object = json_decode($jsonString); echo "Name from object: " . $object->name . "\n"; // Decode as associative array $array = json_decode($jsonString, true); echo "Name from array: " . $array['name'] . "\n"; ?>
Output
Name from object: Alice
Name from array: Alice
Common Pitfalls
Common mistakes when using json_decode include:
- Not checking if the JSON string is valid, which can cause
nullresults. - Forgetting to set the
$assocparameter when you want an array instead of an object. - Not handling errors using
json_last_error()after decoding.
Always verify the JSON string and handle errors gracefully.
php
<?php $jsonString = '{"name":"Bob", "age":30'; // Invalid JSON (missing closing brace) $result = json_decode($jsonString); if (json_last_error() !== JSON_ERROR_NONE) { echo "JSON decode error: " . json_last_error_msg() . "\n"; } else { echo "Decoded successfully."; } ?>
Output
JSON decode error: Syntax error
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| $json | JSON string to decode | Required |
| $assoc | Return associative array if true, object if false | false |
| $depth | Maximum recursion depth | 512 |
| $flags | Bitmask of decode options | 0 |
Key Takeaways
Use json_decode to convert JSON strings into PHP objects or arrays.
Set the second parameter to true to get an associative array instead of an object.
Always check for JSON errors with json_last_error() after decoding.
Invalid JSON strings cause json_decode to return null and set an error.
Use the depth and flags parameters only when needed for advanced decoding.