In this article, I’ll explain how to convert a PHP array into a JSON string and similarly how to convert a JSON string back into PHP array. I’ll use built in Php functions for this purpose.
Convert PHP Array to JSON
To convert array into a JSON string, we use the Php json_encode()
function as per example below:
$arr = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
$json = json_encode($arr );
echo $json;
Output:
{"name":"John","age":30,"city":"New York"}
The above example will convert the associate array into JSON and will print the JSON string.
Convert JSON to PHP Array
Now, to convert a JSON string back into a PHP array, we use the Php json_decode()
function.
$json_str = '{"name":"John","age":30,"city":"New York"}';
$array = json_decode($json_str , true);
print_r($array);
Output:
Array
(
[name] => John
[age] => 30
[city] => New York
)
That’s it! You’ve today successfully learned how to convert PHP arrays to JSON and vice versa.