Converting PHP Array to JSON in PHP

By | October 2, 2020
PHP Array to JSON

Converting an PHP array to JSON in PHP is quite easy and useful. These days while creating API’s almost everyone is using JSON. Also while showing data from database we use to get it in JSON format these days. JSON is accessible in PHP as well as Javascript or Jquery and other languages also.  JSON full name is JavaScript Object Notation. Right now this is the most favorite data format for handling data.

While using PHP its very easy to create a JSON data response by the use of only 1 function and the function is json_encode(). It takes array as parameter and convert it to JSON.

Here is an associative array which we will change to JSON.


$compData = array (       
        "name" => "Vivek Moyal", 
        "role" => "operator"
        "name" => "Vikas Moyal", 
        "role" => "Manager"
        "name" => "Asha Verma", 
        "role" => "CRM"
    ) ,
        "name" => "Gargi", 
        "role" => "Manager"
echo json_encode($compData); 


In the above code last line json_encode will take the PHP array and convert it to JSON. It will return the result as below.

[{"name":"Vivek Moyal","role":"operator"},
{"name":"Vikas Moyal","role":"Manage"},
{"name":"Asha Verma","role":"CRM"},

Hope you like the tutorial if you face any issue then please comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *