Search code examples
phparraysexportvar-dump

How to export PHP array where each key-value pair is in separate line?


I'm looking for equivalent functionality to var_export() which allows me to export PHP array into parseable code, but each statement should be printed in separate line (so each line has its own independent structure).

Currently this code:

<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?>

will output:

array (
  0 => 1,
  1 => 2,
  2 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)

However I'm looking to output into the following format like:

$foo = array()
$foo['0'] = 1
$foo['1'] = 2
$foo['2'] = array();
$foo['2']['0'] = 'a';
$foo['2']['1'] = 'b';
$foo['2']['2'] = 'c';

so execution of it will result in the same original array.

The goal is to manage very large arrays in human understandable format, so you can easily unset some selected items just by copy & paste method (where each line includes the full path to the element). Normally when you dump very big array on the screen, the problem is that you've to keep scrolling up very long time to find its parent's parent and it's almost impossible to find out which element belongs to which and what is their full path without wasting much amount of time.


Solution

  • Currently I've found here (posted by ravenswd) this simple function which can achieve that:

    function recursive_print ($varname, $varval) {
      if (! is_array($varval)):
        print $varname . ' = ' . var_export($varval, true) . ";<br>\n";
      else:
        print $varname . " = array();<br>\n";
        foreach ($varval as $key => $val):
          recursive_print ($varname . "[" . var_export($key, true) . "]", $val);
        endforeach;
      endif;
    }
    

    Output for recursive_print('$a', $a);:

    $a = array();
    $a[0] = 1;
    $a[1] = 2;
    $a[2] = array();
    $a[2][0] = 'a';
    $a[2][1] = 'b';
    $a[2][2] = 'c';