Converting JSON to Array or Object in PHP

While working on JSON (JavaScript Object Notation), we need to convert PHP array or object to JSON or JSON strings to an array.

In our previous tutorial we have explained how to convert an array to JSON in PHP. In this tutorial you will learn how to convert JSON string to array in PHP.

Sometimes we need to convert JSON strings to PHP variable to use in PHP project. So here we will handle this using PHP function json_decode() that decodes a JSON string into an array.

Also, read:

We will cover this tutorial with example code have JSON string and convert to PHP variable. So let’s proceed with it.


Here is the JSON string data that we will convert.

$jsonData = '[{"name":"Jhon Smith","age":"40"}, {"name":"Kane William","age":"50"},
 {"name":"Ian David","age":"30"}]';

Now we will use the json_decode() PHP function to convert to PHP variable. This function returns object by default. The below example code will convert json string to object.

$dataObject = json_decode($jsonData);
// Dump all data of the Object
print_r($dataObject);
// Access object data
echo $dataObject[0]->name; 

We need to pass second Boolean parameter true if want output as array data. The example code will return as associative array.

$dataArray = json_decode($jsonData, true);
// Dump all data of an array
print_r($dataArray);
// Access array data 
echo $dataArray[0]["name"]; 

You may also like: