How to Convert JSON Array to PHP Array
How to Convert JSON Array to PHP Array

How to Convert JSON Array to PHP Array

How to Convert JSON Array to PHP Array

Hello folks, in this tutorial we will learn how to convert JSON array to PHP array.

 

To convert a JSON array to a PHP array, we can use the json_decode() function in PHP. Here’s how we can do it:

<?php
$jsonArray = '["apple", "banana", "orange"]';
$phpArray = json_decode($jsonArray, true);

print_r($phpArray);
?>

Output will be:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)

 

If you already don’t know json_decode() is a PHP built in function used to decode a JSON string into a PHP variable. It takes a JSON-encoded string and converts it into a PHP variable like an array or an object.

Here’s another example of how we can use it:

<?php
$jsonString = '{"name":"John", "age":30, "city":"New York"}';

// Decode JSON string into a PHP associative array
$phpArray = json_decode($jsonString, true);

// Decode JSON string into a PHP object
$phpObject = json_decode($jsonString);

// Output the results
print_r($phpArray);
echo "<br>";
print_r($phpObject);
?>

Output will be following:

Array
(
    [name] => John
    [age] => 30
    [city] => New York
)
stdClass Object
(
    [name] => John
    [age] => 30
    [city] => New York
)

As we can see, json_decode() converts the JSON string into either an associative array (where each element is associated with a specific key, not just numerical indices. This means we can access the elements of the array using their keys instead of their positions in the array) or an object based on whether we provide true as the second argument. If you remove the second argument or set it’s value to false, it will return an object. If we provide true, it will return an regular associative array.

 

That’s all for today. See you in next one!

 

Check Out More Resources:

Articles:
Website: https://laravelplug.com/
YouTube Channel: https://www.youtube.com/channel/UCnTxncHQcBSNs4RCuhWgF-A?sub_confirmation=1
WordPress Playlist: https://www.youtube.com/watch?v=8VvXzFAFwQU&list=PLVoVZqAh8dTLHZ51egvEU7dsOrRCSIMWx
Tools Playlist: https://www.youtube.com/watch?v=gTQoUn3BQkM&list=PLVoVZqAh8dTK-DWHBGWOEEvzvPQrgFne-

WordPress Tutorials: https://laravelplug.com/category/wordpress/
Laravel Tutorials: https://laravelplug.com/category/laravel/
PHP Tutorials: https://laravelplug.com/category/php/
SQL Tutorials: https://laravelplug.com/category/sql/
Various Tips: https://laravelplug.com/category/tips/
Useful Tools: https://laravelplug.com/category/tools/

Socials:

Twitter: https://twitter.com/LaravelPlug
Pinterest: https://www.pinterest.com/LaravelPlugCom/
Facebook: https://www.facebook.com/groups/1020759861842360
Mail: info@laravelplug.com

#PHP #JSON #ARRAY

 

That’s All. Feel free to knock me. Thanks.

 

Editorial Staff

A Learner and trying to share what I learned!