For store associative arrays you can use serialize
:
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3
);
file_put_contents('stored-array.txt', serialize($arr));
And load using unserialize
:
$arr = unserialize(file_get_contents('stored-array.txt'));
print_r($arr);
But if need creat dinamic .php
files with array (for example config files), you can use var_export(..., true);
, like this:
Save in file:
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3
);
$str = preg_replace('#,(\s+|)\)#', '$1)', var_export($arr, true));
$str = '<?php' . PHP_EOL . 'return ' . $str . ';';
file_put_contents('config.php', $str);
Get array values:
$arr = include 'config.php';
print_r($arr);