tags:

views:

72

answers:

5

I just want to quickly store an array which i get from a remote API, so that i can mess around with it on a local host.

So:

  1. i currently have an array
  2. i want to people to use the array without having to get it from the API

There are no needs for efficiency etc here, this isnt for an actual site just for getting some sanitizing/formatting methods made etc

is there a function like store_array() restore_arrray() ?!

+8  A: 

If you don't need the dump file to be human-readable, you can just serialize() the array.

storing:

file_put_contents('yourfile.bin', serialize($array));

retrieving:

$array = unserialize(file_get_contents('yourfile.bin'));
soulmerge
A: 

Use php's serialze:

file_put_contents("myFile",serialize($myArray));
elias
+3  A: 

You can use serialize to make it into a string to write to file, and the accompanying unserialize to return it to an array structure.

I'd suggest using a language independent structure though, such as JSON. This will allow you to load the files using different languages than PHP, in case there's a chance of that later. json_encode to store it and json_decode($str, true) to return it.

Tor Valamo
+1  A: 

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.

retro
your code is wrong. you won't retrieve an array with your code.
Tor Valamo
There is type mismatch on second line. There should be $arr1. Also you need to pass true as second parameter to json_decode to return array.Code updated.
retro
+1  A: 

var_export() does exactly what you want.

It will take any kind of variable, and store it in a representation that the PHP parser can read back.

WishCow
How you can load that var_export() output again ? With eval() ? Try to var_export some Object.
retro
Either with eval, or just simply include() the file.
WishCow