In this article, we will see how to convert a PHP array to a JSON object. We will convert a PHP array into a JSON string using json_encode(). The json_encode() function is an inbuilt function in PHP that is used to convert a PHP array or object into JSON representation.
Many times we require to convert PHP array into JSON array in PHP or laravel application. When you are working with ajax requests at that time you need to send a JSON response because we can get JSON data easily.
Here, I will three different examples of how to convert the PHP array to a JSON object with output. Also, we can force convert JSON objects using the "JSON_FORCE_OBJECT" parameter.
In this example, we will use json_encode() function.
<?php
$colors = ['Red', 'Blue', 'Green', 'Yellow', 'Pink'];
$colorsJSON = json_encode($colors);
echo $colorsJSON;
?>
Output:
["Red","Blue","Green","Yellow","Pink"]
In this example, we will use JSON_FORCE_OBJECT to encode the array object.
<?php
$colors = ['Red', 'Blue', 'Green', 'Yellow', 'Pink'];
$colorsJSONObject = json_encode($colors, JSON_FORCE_OBJECT);
echo $colorsJSONObject;
?>
Output:
{"0":"Red","1":"Blue","2":"Green","3":"Yellow","4":"Pink"}
In this example, we will encode the array key and value.
<?php
$address = ['city'=>'Mumbai', 'place'=>'Taj Hotel'];
$jsonData = json_encode($address);
echo $jsonData;
?>
Output:
{"city":"Mumbai","place":"Taj Hotel"}
I have added 3 examples for your reference, you can use anyone as per your requirements.
You might also like:
- Read Also: Character Count In Textarea
- Read Also: PHP Array Functions With Example
- Read Also: How To Push Array Element In Node.js
- Read Also: Vue Js Get Array Of Length Or Object Length