John123
John123

Reputation: 293

Permanently Push To The End of An Array

How can I do the following:

$x = array();
$x[] = '1';
$x[] = '2';

But have it added permanently to the array?

I have idea on how we could try doing it:

x[] = y[0]; x[] = y[1]; x[] = y[2];

But im wondering is that the best way of doing it?

Upvotes: 3

Views: 199

Answers (2)

FuzzyTree
FuzzyTree

Reputation: 32402

Use serialize on your array, which converts it into a string that you can write to a file

file_put_contents("myfile",serialize($x));

and unserialize to convert the string back into an array

$x = unserialize(file_get_contents("myfile"));

If you only need to append values to the very end of the array, you can use file_put_contents with the FILE_APPEND option, which is faster than reading the entire array into memory and writing it back to disk

file_put_contents("myfile", "1\n", FILE_APPEND);
file_put_contents("myfile", "2\n", FILE_APPEND);

and read the array using file (which uses \n as a delimiter by default)

$x = file("myfile");

Upvotes: 1

Chris
Chris

Reputation: 4810

To save anything "permanently", you need some kind of persistent storage. A txt file would work, database, even cookies code work depending on what you are saving.

file_put_contents()

MySQL

Upvotes: 0

Related Questions