I will divide the answer into three parts: reading the file, modifying it and writing it.
Reading
The require
function normally includes a file to run - but if its return is assigned to a variable, it receives the content returned by that file.
File array.php
:
return array(
'DB_TYPE' => 'mysql',
'DB_USER' => 'root'
);
File index.php
:
$array = require('array.php');
Modification
We changed the desired key, as we would normally do:
$array['DB_TYPE'] = 'pgsql';
Writing
Here we will write the configuration file again using the var_export
function, which exports a variable in a way that can be understood by PHP. In addition, we have inserted the opening tag and other necessary characters so that there is no syntax error when reading the file again.
file_put_contents(
'array.php',
'<?php' . PHP_EOL . PHP_EOL . 'return ' . var_export($array, true) . ';'
);
So, in the end, the script would look like this:
<?php
$array = require('array.php');
$array['DB_TYPE'] = 'pgsql';
file_put_contents(
'array.php',
'<?php' . PHP_EOL . PHP_EOL . 'return ' . var_export($array, true) . ';'
);