What is json_decode() in PHP?
When working with PHP, sometimes we need to fetch data from outer sources (e.g. via HTTP API) and manipulate it inside our program. This data is usually retrieved in JSON format.
In PHP we can decode this data via the json_decode function.
Note: this function works only with UTF-8 string as input.
Syntax
json_decode(
$json,
$associative = null,
$depth = 512,
$flags = 0
): mixed
Parameters
-
$json: This function requires a validjson stringas the first input. -
$associative: It is an optional Boolean value that when specifiedtruereturns an associative array, and when set tofalsereturns an object. -
$depth: This parameter tells how many nested objects the function will decode. Its default value is set to 512. -
$flags: This parameter is used to change the behavior of the function by specifying a BITMAP.
Return values
The function will return an object or an array if everything goes well. Otherwise, it will return false.
Code
<?php$js = '{"name":"educative","args":[1,2,3,4,5]}';// lets decode to an object$jsobj = json_decode($js);var_dump($jsobj);// lets decode to an array$jsarr = json_decode($js, true);var_dump($jsarr);
Explanation
In the first case, only the JSON object is passed to the function and no other values are stated. This results in the default PHP object being created.
In the second example, the second parameter is set to true, making the return value of the function a PHP array instead.