Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
json
communitycreator

What is json_decode() in PHP?

Dario Vincenzo Tarantini

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 valid json string as the first input.

  • $associative: It is an optional Boolean value that when specified true returns an associative array, and when set to false returns 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.

RELATED TAGS

php
json
communitycreator

CONTRIBUTOR

Dario Vincenzo Tarantini

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring