Skip to content
Advertisement

Is PHP possible to print out variable source code as string?

I have a simple variable like this

$arr = [
  'aa' => 'aa',
  'bb' => 'bb'
];

Now, PHP comes with several print out function

print_r

print_r($arr);

result:

Array
(
    [aa] => aa
    [bb] => bb
)

var_dump

var_dump($arr);

result:

array(2) {
  ["aa"]=>
  string(2) "aa"
  ["bb"]=>
  string(2) "bb"
}

I want a function that can print out the original source code like this:

print_out_source_code($arr);

result:

$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”:

$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);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement