The PHP json_decode is an inbuilt Function in PHP that converts a JSON String to PHP Object. For example, it can convert a JSON String to an array in PHP. In this article, we will discuss the PHP json_decode Function. Also, we will discuss a few examples of using it.
Also, in order to convert a PHP object to a JSON String, you can use the PHP json_encode Function.
Syntax
mixed json_deocde($json, $assoc = false, $depth = 512, $options = 0)
Parameters
The PHP json_decode Function expects one mandatory and three optional parameters. The description of the parameters is given below as follows:
- $json: The first parameter is the mandatory JSON which the function will decode.
- $assoc: When the value of $assoc is true, the function will return an associative array. However, by default the value is false and the function returns a class object.
- $depth: User specified recursion depth. The default value to this parameter is 512.
- $options: You can also pass optional bitmasking options to the json_encode Function in PHP. The behavior of the constants is defined on JSON Constants Page.
Return Value
The PHP json_decode Function returns the encoded JSON string to the corresponding PHP data type. However, it returns NULL on failure.

Examples
Example 1: JSON to Object
By default the function returns a class object.
<?php $jsonString = '{"Users":[{"First":"Chandler","Last":"Bing"},{"First":"Rachael","Last":"Green"},{"First":"Ross","Last":"Geller"}]}'; print_r(json_decode($jsonString)); ?>
The output of the above code snippet will be as follows:
stdClass Object
(
[Users] => Array
(
[0] => stdClass Object
(
[First] => Chandler
[Last] => Bing
)
[1] => stdClass Object
(
[First] => Rachael
[Last] => Green
)
[2] => stdClass Object
(
[First] => Ross
[Last] => Geller
)
)
)
Example 2: JSON to PHP Array
Alternatively, you can also convert the JSON value to an associative array by passing true in the second parameter.
<?php $jsonString = '{"Users":[{"First":"Chandler","Last":"Bing"},{"First":"Rachael","Last":"Green"},{"First":"Ross","Last":"Geller"}]}'; print_r(json_decode($jsonString, true)); ?>
Array
(
[Users] => Array
(
[0] => Array
(
[First] => Chandler
[Last] => Bing
)
[1] => Array
(
[First] => Rachael
[Last] => Green
)
[2] => Array
(
[First] => Ross
[Last] => Geller
)
)
)
Conclusion
In this article, we discussed the PHP json_decode Function. It is used to convert a JSON String to PHP data type. You can use the PHP json_encode Function to convert a PHP data type to a valid JSON.
Read more about json_decode on PHP Official Documentation.

Vishesh is currently working as a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.