In this tutorial, you shall learn how to parse a JSON string in PHP using json_decode() function, with syntax and example programs.

PHP – Parse JSON String

To parse a JSON String in PHP, call json_decode() function and pass the JSON string. This function can take other optional parameters also that effect the return value or parsing.

Syntax

The syntax of json_decode() function is

</>
Copy
json_decode(string, associative, depth, flags)

where

ParameterDescription
string[Required] JSON string to be parsed or decoded.
associative[Optional] Boolean Value. If true, the returned object will be converted into an associate array. If false (default value), an object is returned.
depth[Optional] Integer. Specifies the depth of recursion. Default value = 512.
flags[Optional] Bitmask: JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR

Generally, the first two parameters are sufficient in most use cases while parsing a JSON string. The other two parameters are used only in some special scenarios.

Examples

1. Parse JSON array string into a PHP array

In this example, we will take a JSON string and parse it using json_decode() function with the default optional parameters. We shall display the object returned by json_decode() in the output.

PHP Program

</>
Copy
<?php
$jsonStr = '{"apple": 25, "banana": 41, "cherry": 36}';
$output = array(json_decode($jsonStr));
var_dump($output);
?>

Output