How to JSON Decode a String into an Array with PHP

Sometimes, while trying to decode a JSON to an array, most developers meet errors. If you have also faced such an issue in your programming practice, then this snippet is for you.

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

Watch a course Learn object oriented PHP

Using json_decode

According to PHP documentation, it is necessary to indicate whether you wish to get an associative array rather than an object from json_decode the code will look as follows:

<?php

json_decode($jsondata, true);

?>

Using the assoc Parameter of json_decode

In the json_decode function, there is a parameter known as assoc. It is aimed at converting the returned objects to associative arrays.

Here is how it looks like:

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

But, note that since the assoc parameter is set to FALSE, it is necessary to set it to TRUE for retrieving an array.

Here is another example:

<?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:

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 json_decode function is used for taking a JSON encoded string and converting it into a PHP variable.

It has four parameters: json, assoc, depth, and options.

Once the assoc parameter is TRUE, then the returned objects will be converted to associative arrays.

The json_encode function is capable of returning the value encoded in JSON in an appropriate PHP type.