0

I'm building something in PHP which reads from a PHP file, which looks like this:

<?php

return [
'name' => 'John Smith'
];

In my code, I'm getting the contents of the file and I'm reading it. But here's my problem. When I want to add an item to that array, I can but I'm not sure how to save it back into that array file.

I've tried these ways of doing it ($array being the updated array)

file_put_contents('file.php', var_export($array, true));
file_put_contents('file.php', print_r($array, true));
2
  • Hmmm what is return_r() when it is at home with its boots off? Commented Jul 11, 2019 at 13:26
  • Check what var_export($array, true) actually gives you, then figure out which missing parts around it you have to add yourself. Commented Jul 11, 2019 at 13:27

2 Answers 2

1

Put back the array in your file using var_export() like this :

file_put_contents('file.php', '<?php return ' . var_export($array, true) . ';');

Sign up to request clarification or add additional context in comments.

Comments

0

As I see @misorude already suggested you need parameter 2 of var_export to be set to true as below

$ids = ['t1'=>10, 't2'=> 12, 't3' => 5];

$str = '<?php ' . PHP_EOL
        . 'return '
        . var_export($ids, 1) . ';' ;

echo $str;

RESULT:

<?php 
return array (
  't1' => 10,
  't2' => 12,
  't3' => 5,
);

So just write $str to a file and you are done

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.