tags:

views:

50

answers:

4

Is there any way to pass an array between two pages intact?

I am building a huge array, and the building of it uses masses of memmory. I would like to be able to store the array intact and then reaccess it from another page?

If I use $x = print_r($array,true); and write it to a file, how could I then rebuild it into an array, or is there a better way altogether.

+1  A: 

You could easily store that data in the session. Like this

$_SESSION['serialized_data'] = urlencode(serialize($your_data));

and then afterwards on your second page:

$your_data = unserialize(urldecode($_SESSION[$serialized_data]));

I use this approach quite often.

Michael
If find it more suitable writing the data to a file you can use a similar approach of serializing/unserializing.
Michael
Note that if you are using object references they cannot be serialized.
Michael
+1  A: 

You can store it in session ( not sure how big it is ) .. if you want to write to file .. you can do something like this:

$fp = fopen("file.php" , "w");
fwrite($fp , "<? \$array = ".var_export($array,true).";");
fclose($fp);

and then just include that file like a normal file on next page loads.

Sabeen Malik
@Sabeen Malik: The `serialize` function is better in such situation :)
Sarfraz
@Sarfraz .. need to keep the target audience in mind :)
Sabeen Malik
A: 

Passing huge amounts of data between pages generally isn't a great decision, but there can be exceptions - what are you trying to accomplish here?

I wouldn't suggest using session variables. In many cases, if the data seems to large to pass between pages, it is. In those cases, it may be useful to use a database for the information and access the database from each page.

Jeff Meyers
A: 

Easiest way would be to use a session variable.

$_SESSION['big_array']=$big_array;

This wouldn't be particularly advisable if it's a high volume site (as the arrays will sit in memory until sessions expire) but should be fine otherwise.

You'll want to make sure you've started the session prior which, if necessary, can be done using:

session_start();
Goat Master