+3 votes
in Programming Languages by (5.8k points)
I want to store an associate array of PHP to a file so that I can load it later. In Python, one can use the pickle module to save and load a dictionary. Is there any similar module in PHP?

If not, how can I save and load an associative array?

1 Answer

0 votes
by (25.1k points)

To store an array to a file, you can serialize() the array and store it in a file.

When you want to read the array again, you can unserialize() the file content.

Here is an example to show how to store and load an associative array of PHP:

<?php
$view_count = array (
    'a1'=> 100,
    'a2'=> 120,
    'a3'=> 124,
    'a4'=> 139,
    'a5'=> 125
);

// store the array
file_put_contents("view_count.bin", serialize($view_count));

// load the saved array
$view_count1 = unserialize(file_get_contents("view_count.bin"));

print_r($view_count1);

if ($view_count === $view_count1){
    print("same array\n");
}

?>

The above code will display the following output:

Array
(
    [a1] => 100
    [a2] => 120
    [a3] => 124
    [a4] => 139
    [a5] => 125
)
same array

...