I have a simple variable like this
JavaScript
x
$arr = [
'aa' => 'aa',
'bb' => 'bb'
];
Now, PHP comes with several print out function
print_r
JavaScript
print_r($arr);
result:
JavaScript
Array
(
[aa] => aa
[bb] => bb
)
var_dump
JavaScript
var_dump($arr);
result:
JavaScript
array(2) {
["aa"]=>
string(2) "aa"
["bb"]=>
string(2) "bb"
}
I want a function that can print out the original source code like this:
JavaScript
print_out_source_code($arr);
result:
JavaScript
$arr = [
'aa' => 'aa',
'bb' => 'bb'
];
Is there any function that can achieve this?
Advertisement
Answer
This should work for the exact “restore array” you’re asking.
Try “var_export” and “eval”:
JavaScript
$arr = [
'aa' => 'aa',
'bb' => 'bb'
];
$filename = 'arr_test.txt';
// save the export, evaluable code of the variable:
$bytes = file_put_contents($filename, var_export($arr, true));
print_r($arr);
// restoring the arr from saved "source code"
$arr = null;
eval('$arr = '.file_get_contents($filename).';');
print_r($arr);