Skip to main content

Command Palette

Search for a command to run...

How To Convert PHP Array To JSON Object

Published
1 min read
W

The websolutionstuff is to help for beginner programmers who want to start career in web development or learn web development technologies or languages.

In this example I will show you how to convert PHP array to JSON object, We will convert PHP array into json string using json_encode().

The json_encode() function is an inbuilt function in PHP which is used to convert 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 request at that time you need to send json response because we can get json data easily .

Here,I will 3 different examples of how to convert PHP array to JSON object with output, Also we can force convert json object using "JSON_FORCE_OBJECT" parameter.

Example 1 :

<?php

  $colors = ['Red', 'Blue', 'Green', 'Yellow', 'Pink'];

  $colorsJSON = json_encode($colors);

  echo $colorsJSON;

?>

Output :

["Red","Blue","Green","Yellow","Pink"]

Example 2 :

<?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"}

Example 3 :

<?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 references, you can use anyone as per your requirements.


Read Also : Character Count In Textarea