store PHP array in a Database

How to store PHP array in a Database?

How we can store a PHP array in a database?

To store a PHP array in any database, we have to convert the array into a string, then we can store that array as a string.

After fetching the array string from the database, we have to convert the converted array string back to a PHP array.

How to do?

In PHP, there are two built-in functions serialize() and unserialize()

  • serialize() – Converts an array to a storable representation of a value.
  • unserialize() – To make the serialized string into a PHP array again.
<?php
$fruits = ["Apple", "Banana", "Watermelon"];

// Save it to the database
$arrayToBeStored = serialize($fruits);
echo $arrayToBeStored;

echo "\n --- \n";

// After fetching, convert it back to a php array
$my_fruits = unserialize($arrayToBeStored);
print_r($my_fruits);
a:3:{i:0;s:5:"Apple";i:1;s:6:"Banana";i:2;s:10:"Watermelon";}
 --- 
Array
(
    [0] => Apple
    [1] => Banana
    [2] => Watermelon
)