array to json php – How to convert php array to json object with example?

Rate this post

array to json php – The json_encode() function is an inbuilt function in PHP. It’s used to convert the value of the array into JSON data.

Free Live Chat for Any Issue

array to json php – PHP Array to JSON Array using json_encode();

To convert String to JSON in PHP, use the json_encode() function. this function is useful to convert String to JSON object.

Example 1: php convert array to json object

<?php
  
  $websites = ['PHP', 'pakainfo', 'infinityknow', 'w3school', 'w3diy'];
  
  $websitesJSON = json_encode($websites);
  
  echo $websitesJSON;
  
?>

Result

["PHP","pakainfo","infinityknow","w3school","w3diy"]

Don’t miss : PHP Converting An Array To JSON Tutorial With Example

Read Also:  how to get current url in codeigniter with Examples

Example 2: php convert json object to associative array

<?php
  
  $websites = ['PHP', 'pakainfo', 'infinityknow', 'w3school', 'w3diy'];
   
  $websitesJSONObject = json_encode($websites, JSON_FORCE_OBJECT);
   
  echo $websitesJSONObject;
    
?>

Result

{"0":"PHP","1":"pakainfo","2":"infinityknow","3":"w3school","4":"w3diy"}

Don’t miss : php convert array to json

Example 3: php convert object to array json_encode

<?php
  
  $details = ['name'=>'Ridham', 'blogname'=>'pakainfo.com'];
  
  $jsonDetails = json_encode($details);
  
  echo $jsonDetails;
     
?>

Result

{"name":"Ridham","blogname":"pakainfo.com"}

Download

I hope you get an idea about array to json php.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.