Best ways to store PHP arrays to data sources

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

How to store PHP array

<?php
 
$array = [
   "HotelName" => "Shelton Inn",
   "RoomRate"  => "200",
   "Currency"  => "USD",
   "Amenities" => ["Free Wi-fi","Gym and Spa","Free Parking", "Complimentary buffet"],
];
 
// Encode array into JSON and store
$jsonEncoded = json_encode($array, JSON_PRETTY_PRINT);

// Serialize array and store
$serialize = serialize($array);

// Now you can store the formatted array in MySQL or other data storage
?>

Stay tuned until the end to learn more about storing PHP arrays.

Introduction

PHP arrays are fundamental data structures for storing multiple data objects in memory. However, most real-time applications require data persistence which means storing data permanently in a data source – usually a database or a file in more simple applications. 

Data storage is the last step, and before that, PHP needs to convert the array to a data exchange format like JSON, CSV, or just text. This article explores some best ways to store PHP arrays to data sources. So, stay tuned to the end to know more.

#1 – Store PHP array with json_encode

PHP json_encode function returns a JSON representation of a value. JSON is a popular data exchange format frequently used across many different applications for data exchange. That’s one reason why it is a preferable way to store PHP arrays. The other reason is that the json_encode performs more efficiently than serialize, something we see in the next section.

json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false

The function receives optional flags that alter its behavior. We will pass in a flag JSON_PRETTY_PRINT to get a nice readable JSON output on the console. There are a bunch of flags listed in the official documentation.

Example

Let JSON encode a PHP array and see the output on the console. Now, you can store the JSON in a file or a database. That’s up to you. Here’s more about reading and writing files in PHP.

<?php
 
$array = [
   "HotelName" => "Shelton Inn",
   "RoomRate"  => "200",
   "Currency"  => "USD",
   "Amenities" => ["Free Wi-fi","Gym and Spa","Free Parking", "Complimentary buffet"],
];
 
echo json_encode($array, JSON_PRETTY_PRINT);
 
?>

Here’s the output on the console. It is more readable thanks to the JSON_PRETTY_PRINT flag.

{
    "HotelName": "Shelton Inn",
    "RoomRate": "200",
    "Currency": "USD",
    "Amenities": [
        "Free Wi-fi",
        "Gym and Spa",
        "Free Parking",
        "Complimentary buffet"
    ]
}

Voila! PHP store array as JSON with json_encode. Next, let’s see serialize in PHP.

#2 – Store PHP array with serialize

Serialize in PHP returns a storable representation of a value. It is a hard-to-read text that PHP encodes and decodes. Obviously, it is not preferable if you are working across different languages. Still, it works pretty well for PHP.

serialize(mixed $value): string

Let’s see how to serialize a PHP array.

Example

Let’s reuse the array from the last example and see the output on the console.

<?php
 
$array = [
   "HotelName" => "Shelton Inn",
   "RoomRate"  => "200",
   "Currency"  => "USD",
   "Amenities" => ["Free Wi-fi","Gym and Spa","Free Parking", "Complimentary buffet"],
];
 
echo serialize($array);
 
?>

Here’s the output.

a:4:{s:9:"HotelName";s:11:"Shelton Inn";s:8:"RoomRate";s:3:"200";s:8:"Currency";s:3:"USD";s:9:"Amenities";a:4:{i:0;s:10:"Free Wi-fi";i:1;s:11:"Gym and Spa";i:2;s:12:"Free Parking";i:3;s:20:"Complimentary buffet";}}

See! The output is weird and unreadable. As already mentioned, it is not a portable data exchange format. PHP has a function to decode this text with unserialize. However, it would be a problem if you start working with this data in other languages – say, Javascript.

PHP json_encode vs. serialize

Just to reiterate, JSON and Serialize are two ways to store PHP arrays. JSON is a popular data exchange format with better readability and portability. On the other hand, Serialize lacks these two features and limits its use to PHP only.

It also doesn’t make sense to store serialized text in a relational database, making your database non-portable and complex. Also, benchmarks reveal that the json_encode function performs better than the serialize function. 

Learn more about the difference between these two functions in PHP serialize vs. json_encode in PHP.

Wrap Up

This article explores ways to store PHP arrays to data sources. First, it overviews json_encode that PHP uses to store array as JSON. Finally, it overviews the serialize function and mentions some of its downsides relative to the json_encode. It also features a comparison section of these two functions.

That’s all for this article. Read similar articles about PHP at FuelingPHP

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.