Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permanently Push To The End of An Array

Tags:

arrays

php

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:

  • Make a new .txt file;
  • Write for example: 1~2~3;
  • Use file_get_contents to apply it to a variable $y;
  • Apply explode();
  • Now we can do:

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

  • Add that to a foreach loop;
  • Then somehow use fwrite() or file_put_contents() maybe? to add the variable I want to add to the array so we would use fwrite or something to add to the .txt file?

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

like image 644
John123 Avatar asked Nov 27 '25 07:11

John123


1 Answers

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");
like image 164
FuzzyTree Avatar answered Nov 28 '25 21:11

FuzzyTree



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!