# How To Convert PHP Array To JSON Object

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() function.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 diffrent 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', 'Green', 'Blue'];
  
  $colorsJSON = json_encode($colors);
  
  echo $colorsJSON;
  
?>
```

Output :

```
["Red","Green","Blue"]
``` 

> Example 2 : 
 
```
<?php
  
  $colors = ['Red', 'Green', 'Blue'];
  
  $colorsJSONObject = json_encode($colors, JSON_FORCE_OBJECT);
  
  echo $colorsJSONObject;
  
?>
```

Output :  

```
{"0":"Red","1":"Green","2":"Blue"}
``` 

> Example 3 : 
 
```
<?php
  
  $address = ['city'=>'Delhi', 'place'=>'Red Fort'];
  
  $jsonData = json_encode($address);
  
  echo $jsonData;
     
?>
```

Output :

```
{"city":"Delhi","place":"Red Fort"}
```

I have added 3 examples for your references, you can use anyone as per your requirments. 

---

You might also like :

- [Read Also : How To Create Dependent Dropdown In Laravel](https://techsolutionstuff.com/post/how-to-create-dependent-dropdown-in-laravel)
- [Read Also : Laravel AJAX CRUD Example Tutorial](https://techsolutionstuff.com/post/laravel-ajax-crud-example-tutorial)
- [Read Also : How To Add Summernote Editor In Laravel 8](https://techsolutionstuff.com/post/how-to-add-summernote-editor-in-laravel-8)
