Convert PHP Array to JSON Formatted Text in PHP

In this tutorial, we will introduce the way to convert a php array to json string. We will use json_encode() to convert.

1. Create a php array

$array_for_json = array("value 1", "value 2", "value 3", "value 4");

2. Convert php array to json text

$create_json = json_encode($array_for_json);
echo $create_json;

Then you will get:

["value 1","value 2","value 3","value 4"]

3. We also can convert a php associative array

<?php
$json_arr = array(
'obj 1' => "value 1",
'obj 2' => "value 2",
'obj 3' => "value 3"
);
echo json_encode($json_arr, JSON_PRETTY_PRINT);
?>

Then you will get:

{
    "obj 1": "value 1",
    "obj 2": "value 2",
    "obj 3": "value 3"
}