ItSolutionStuff.com

How to Convert Array to JSON in PHP?

By Hardik Savani • May 14, 2024
PHP JSON

In this example, we will lean to how to convert json objects of array into the php array. we will convert php array into json string. we can convert json object to associative array in php using json_encode. we can also force convert json object by "JSON_FORCE_OBJECT" parameter.

We many times require to convert php array to json array in php application like if you are creating any web services. you always need to send data as json response. Also when you are working with ajax request at that time also you need to send json response because it will easily to getting data and display them.

In this tutorial, you can see bellow example with simple way to converting json object of php array example. also with force convert json object and php convert json object to associative array. So let's there are three example so you can use anything that you require.

Example 1:

<?php

$languages = ['PHP', 'Java', 'JQuery', '.Net', 'Javascript'];

$languagesJSON = json_encode($languages);

echo $languagesJSON;

?>

Output:

["PHP","Java","JQuery",".Net","Javascript"]

Example 2:

<?php

$languages = ['PHP', 'Java', 'JQuery', '.Net', 'Javascript'];

$languagesJSONObject = json_encode($languages, JSON_FORCE_OBJECT);

echo $languagesJSONObject;

?>

Output:

{"0":"PHP","1":"Java","2":"JQuery","3":".Net","4":"Javascript"}

Example 3:

<?php

$details = ['name'=>'Hardik', 'website'=>'itsolutionstuff.com'];

$jsonDetails = json_encode($details);

echo $jsonDetails;

?>

Output:

{"name":"Hardik","website":"itsolutionstuff.com"}

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel PHP json_decode without quotes Example

Read Now →

PHP Move File from One Folder to Another Example

Read Now →

How to Partially Hide Email Address in PHP?

Read Now →

PHP Dropzone Display Existing Files from Server Example

Read Now →

PHP MySQL Column Sorting Example Tutorial

Read Now →

How to Convert Array Values to Lowercase in PHP?

Read Now →

How to Remove Specific Element by Value from Array in PHP?

Read Now →

How to Remove undefined Value from Array in JQuery?

Read Now →

How to Get Maximum Key Value of Array in PHP?

Read Now →

How to Remove Empty Values from Array in PHP?

Read Now →

How to Add Prefix in Each Key of PHP Array?

Read Now →

How to Get Minimum Key Value of Array in PHP?

Read Now →

How to Remove Null Values from Array in PHP?

Read Now →