Orr Siloni
Orr Siloni

Reputation: 1308

PHP dump variable as PHP code

I'm looking for a function to dump a multi-dimension array so that the output is valid php code.

Suppose I have the following array:

$person = array();
$person['first'] = 'Joe';
$person['last'] = 'Smith';
$person['siblings'] = array('Jane' => 'sister', 'Dan' => 'brother', 'Paul' => 'brother');

Now I want to dump the $person variable so the the dump string output, if parsed, will be valid php code that redefines the $person variable.

So doing something like:

dump_as_php($person);

Will output:

$person = array(
    'first'    => 'Joe',
    'last'     => 'Smith',
    'siblings' => array(
        'Jane' => 'sister',
        'Dan'  => 'brother',
        'Paul' => 'brother'
    )
);

Upvotes: 2

Views: 1311

Answers (2)

Gordon
Gordon

Reputation: 316969

serialize and unserialize

This is useful for storing or passing PHP values around without losing their type and structure. In contrast to var_export this will handle circular references as well in case you want to dump large objects graphs.

The output will not be PHP code though.

Upvotes: 0

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340221

var_export()

var_export() gets structured information about the given variable. It is similar to var_dump() with one exception: the returned representation is valid PHP code.

Upvotes: 6

Related Questions