W3docs

How to JSON Decode a String into an Array with PHP

This is a short guideline that provides comprehensive information on how to decode a JSON string into an array with the help of PHP.

Sometimes, while trying to decode a JSON string into an array, developers encounter errors. If you have faced this issue, this snippet is for you.

Here, we will show ways to overcome difficulties like that.

Using json_decode

According to PHP documentation, you must specify whether you want an associative array or an object. To get an array, pass true as the second argument to <kbd class="highlighted">json_decode</kbd>. The code will look as follows:

php json_decode

<?php

// $jsondata should contain a valid JSON string
json_decode($jsondata, true);

?>

Using the assoc Parameter of json_decode

In the <kbd class="highlighted">json_decode</kbd> function, there is a parameter known as assoc. It is aimed at converting the returned objects to associative arrays.

Here is the syntax:

php json_decode assoc

mixed json_decode ( string $json [, bool $assoc = FALSE ] )

Note that since the assoc parameter defaults to FALSE, you must set it to TRUE to retrieve an array.

Here is another example:

php json_decode

<?php

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

The outputs of the code above are:

php json_decode output

object(stdClass)#1 (5) {
  ["a"] => int(1)
  ["b"] => int(2)
  ["c"] => int(3)
  ["d"] => int(4)
  ["e"] => int(5)
}
array(5) {
  ["a"] => int(1)
  ["b"] => int(2)
  ["c"] => int(3)
  ["d"] => int(4)
  ["e"] => int(5)
}

About json_decode in PHP

The <kbd class="highlighted">json_decode</kbd> function is used for taking a JSON encoded string and converting it into a PHP variable.

It has four parameters: <kbd class="highlighted">json</kbd>, <kbd class="highlighted">assoc</kbd>, <kbd class="highlighted">depth</kbd>, and <kbd class="highlighted">options</kbd>.

Once the <kbd class="highlighted">assoc</kbd> parameter is TRUE, the returned objects will be converted to associative arrays.