Convert PHP Array To JSON Object
This tutorial is for How to Convert PHP Array To JSON Object. We will convert the PHP array to JSON string using json_encode(). The json_encode() function is an in-built PHP function that is used to convert a PHP array or object into JSON representation. We are many times required to convert PHP arrays to JSON arrays to convert our PHP or Laravel application. we will 3 different examples of converting a PHP array to a JSON object.
Example 1
<?php $language = ['PHP', 'Python', 'HTML', 'JAVA', 'JavaScript']; $language_json = json_encode($language); echo $language_json; ?> Output: ["PHP","Python","HTML","JAVA","Javascript"]
Example 2
<?php $language = ['PHP' => 'Laravel', 'Python' => 'django' , 'JavaScript' => 'Jquery']; $language_json = json_encode($language); echo $language_json; ?> Output: {"PHP":"Laravel","Python":"django","Javascript":"Jquery"}
Example 3
We can force-convert JSON objects using JSON_FORCE_OBJECT
parameter.
<?php $language = ['PHP', 'Python', 'HTML', 'JAVA', 'JavaScript']; $language_json = json_encode($language, JSON_FORCE_OBJECT); echo $language_json; ?> Output: {"0":"PHP","1":"Python","2":"HTML","3":"JAVA","4":"Javascript"}