Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array from output of var_dump in PHP?

Tags:

php

var-dump

How can I parse the output of var_dump in PHP to create an array?

like image 517
omg Avatar asked Sep 15 '09 08:09

omg


3 Answers

Use var_export if you want a representation which is also valid PHP code

$a = array (1, 2, array ("a", "b", "c"));
$dump=var_export($a, true);
echo $dump;

will display

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

To turn that back into an array, you can use eval, e.g.

eval("\$foo=$dump;");
var_dump($foo);

Not sure why you would want to do this though. If you want to store a PHP data structure somewhere and then recreate it later, check out serialize() and unserialize() which are more suited to this task.

like image 85
Paul Dixon Avatar answered Oct 19 '22 00:10

Paul Dixon


I had a similar problem : a long runing script produced at the end a vardump of large array. I had to parse it back somehow for further analyzis. My solution was like this:

cat log.stats  | 
  sed 's/\[//g' | 
  sed 's/\]//g' | 
  sed -r 's/int\(([0-9]+)\)/\1,/g' | 
  sed 's/\}/\),/g' | 
  sed -r 's/array\([0-9]+\) \{/array(/g' > 
  log.stats.php
like image 30
qbolec Avatar answered Oct 19 '22 02:10

qbolec


You can't. var_dump just outputs text but doesn't return anything.

like image 31
Joey Avatar answered Oct 19 '22 01:10

Joey