Categories
PHP

Convert PHP Array To JSON : Examples

This tutorial focuses on converting PHP Array to JSON. It is used to read data from the server and display it to the Web. JSON is a text format , and We can convert any JS Object into a JSON format.

  1. Covert PHP array to JSON

PHP is capable of handling JSON and it has some built-in functions to handle them. json_encode() is used to convert objects, arrays in PHP to JSON format. The PHP json_encode() function returns the string containing a JSON equivalent of the value passed.

The syntax of json_encode() function as following.

json_encode(value, options)

Here’s how we need to convert the numerically indexed array into JSON

<?php
$names = ['Bishrul', 'Bishrul Haq', 'Developer', 'Software Engineer'];
$namesJSON = json_encode($names);
echo "Names in JSON :".$namesJSON;

Output :

Names in JSON :["Bishrul","Bishrul Haq","Developer","Software Engineer"]

If you want the array to be output as Object , you can use JSON_FORCE_OBJECT option as below,

<?php
$names = ['Bishrul', 'Bishrul Haq', 'Developer', 'Software Engineer'];
$namesJSON = json_encode($names,JSON_FORCE_OBJECT);
echo "Names in JSON :".$namesJSON;

Output :

Names in JSON :{"0":"Bishrul","1":"Bishrul Haq","2":"Developer","3":"Software Engineer"}
  1. Convert PHP Associative Array to JSON

To Convert a key-value pair array (Associative Array), you can also use json_encode() to convert objects, arrays in PHP to JSON format.

Here’s how we need to convert an associative array into JSON

<?php
$names = ['Name'=>'Bishrul', 'Full Name'=>'Bishrul Haq', 'Details'=>'Developer', 'Designation'=>'Software Engineer'];
$namesJSON = json_encode($names);
echo "Names in JSON :".$namesJSON;

Output :

Names in JSON :{"Name":"Bishrul","Full Name":"Bishrul Haq","Details":"Developer","Designation":"Software Engineer"}

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Latest Posts

Leave a Reply

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