I'd like to save an array to disk so that I can easily read it back into an array. What would be an easy way to do this?
-
...information? It's an array of associative arrays. – MikeJerome Oct 18 '11 at 05:51
-
1Strings? Numbers? Objects? Ponies? – Ignacio Vazquez-Abrams Oct 18 '11 at 05:53
-
An array of associative arrays of strings. array[0] = array('pony id' => "127tk", 'pony owner' => "me", 'pony size' => "little") – MikeJerome Oct 18 '11 at 05:53
3 Answers
file_put_contents($file, serialize($array));
And read it back by
$array = unserialize(file_get_contents($file));
Edit: You can also use json_encode/json_decode instead. Check this question Preferred method to store PHP arrays (json_encode vs serialize) to get more information.
One issue is that serialize()
is not guaranteed to be portable between different applications - it's ONLY designed to be readable by PHP. PHP don't even guarantee that it will be portable between different PHP versions.
Therefore, serialize()
is great for local temporary data because it's fast, but if you want something to be more permanent, and highly portable, I'd use json_encode()
.
Then use json_decode()
, obviously, to decode it.

- 114,488
- 30
- 148
- 167
For a benchmark test of three methods -JSON, serialization, var_export- see http://techblog.procurios.nl JSON is probably best for large (>50 Mb) arrays although it works only with UTF-8 encoded data.

- 57
- 8