23

I have a PHP file to store an array:

<?php
  $arr = array (
    "A" => "one",
    "B" => "two",
    "C" => "three"
  );
?>

I am using require to open the file, and each entry loads into a form. (foreach loop) I would like to save the $_POST variables back (overwriting) to the original file in the same format. I have no trouble making the form and sending back the variables. I just need a way to print the array back into the original file.

Example result:

<?php
  $arr = array (
    "A" => "new value",
    "B" => "other new value",
    "C" => "third new value"
  );
?>

I have been unable to use print_r, as the format returned is incorrect. How can I do this successfully? Thank you.

3
  • 1
    Why not just use json_encode() and json_encode() if you really want to save the array / object to a file? Or serialize() and unserialize().
    – WWW
    Aug 20, 2013 at 18:34
  • I didn't got what you are trying here
    – Mr. Alien
    Aug 20, 2013 at 18:35
  • 1
    var_export() comes closes to what you want, but there's no built-in PHP function that'd export a structure as executable PHP code. Use serialize() or json_encode() to store the data.
    – Marc B
    Aug 20, 2013 at 18:41

3 Answers 3

67

The function you're looking for is var_export

You would use it like this

file_put_contents($filename, '<?php $arr = ' . var_export($arr, true) . ';');

DEMO

0
7

You probably don't want to be re-writing your php code on the fly.

Two alternatives:

  1. Use a database

  2. Serialize the array, then (over)write to file. When reading the file, you will just want to unserialize the value.

  3. Use json_encode and json_decode as discussed in #2

3
  • I would like to be able to manually edit the file containing the array; the serialized array is not very readable when you have numerous entries.
    – Mooseman
    Aug 20, 2013 at 18:40
  • 1
    json_encode / json_decode is definitely a workable alternative that will result in something a bit more readable/editable. Aug 20, 2013 at 18:42
  • There are use cases where writing a php file with an array makes sense. E.g. writing of sensitive config files at app install.
    – markus
    Oct 31, 2013 at 8:31
3

There's actually several ways to achieve that.

  1. Open your file and write into it with file_put_contents() (http://php.net/manual/fr/function.file-put-contents.php)
  2. write to the file your array encoded to string with JSON.encode (http://www.php.net/manual/fr/function.json-encode.php)
  3. read your file with file_get_contents (file_get_contents)
  4. convert your string to an array with JSON.decode (http://www.php.net/manual/fr/function.json-decode.php)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.