How do I store an array in a file to access as an array later with PHP?

The best way to do this is JSON serializing. It is human readable and you’ll get better performance (file is smaller and faster to load/save). The code is very easy. Just two functions

Example code:

$arr1 = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
file_put_contents("array.json",json_encode($arr1));
# array.json => {"a":1,"b":2,"c":3,"d":4,"e":5}
$arr2 = json_decode(file_get_contents('array.json'), true);
$arr1 === $arr2 # => true

You can write your own store_array and restore_array functions easily with this example.

For speed comparison see benchmark originally from Preferred method to store PHP arrays (json_encode vs serialize).

Leave a Comment