PHP: json_decode() | How to decode json to array in PHP

By Parth Patel on Sep 09, 2021

The json_decode() is an inbuilt function in php which is used to convert JSON encoded string to appropriate variable in php.

Generally, json_decode is used to convert json to array in PHP but it has other usecases as well.

Syntax:

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

Parameters:

  • json: The JSON string passed to be decoded to php variable. This function only works with UTF-8 encoded strings.
  • assoc: It is a boolean variable. When true is passed, JSON object will be converted into associative array; when false is passed, JSON object will be returned as stdClass object; when NULL is passed, it will return associative array or object depending on the JSON_OBJECT_AS_ARRAY flag.
  • depth: Maximum nesting depth of the JSON to be decoded.
  • flags: It includes bitmask of JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING,, JSON_THROW_ON_ERROR and other JSON constants.

Return:

The json_decode() function decodes the JSON string to appropriate PHP type based on the parameter.

When true, false, or null is passed for JSON, the function returns same true, false, or null respectively. If the JSON failed to be decoded or the JSON is deeper than given depth then null gets returned.

How to decode json to array in PHP

Example:

<?php

// Store JSON data in a PHP variable
$json = '{"John":20,"Harry":30,"Dave":40,"Tony":50}';
 
var_dump(json_decode($json,true));

?>

Output:

array(4) {
  ["John"]=>
  int(20)
  ["Harry"]=>
  int(30)
  ["Dave"]=>
  int(40)
  ["Tony"]=>
  int(50)
}

How to decode json to object in PHP

If you don't pass second parameter, or pass false, json_decode() will parse JSON to stdClass object therefore you can use "→" arrow notation to access the object properties.

Example:

<?php

// Store JSON data in a PHP variable
$json = '{"email":"john@doe.com"}';

$obj = json_decode($json);
print $obj->email;

?>

Output:

john@doe.com

Conclusion

Here's the simple explanation to how json_encode() works and how you can parse json to array or class objects in PHP.

Adios