Solution : Using var_export
If you want to capture structured debug output as a string, var_export() is a good option. Unlike var_dump(), it has a second parameter $return which, when set to true, makes it return the output instead of printing it:
$debug = var_export($myVar, true);
✅ Why use this?
Cleaner one-liner (no need for ob_start() / ob_get_clean()).
Produces output that is valid PHP code, so you could even eval() it if needed.
Generally easier to read for many cases.
⚠️ Difference from var_dump:
var_export → returns a parsable PHP code representation of the variable.
var_dump → outputs detailed debug info, including types and lengths.
For resources, var_export just returns NULL.
Demo:
$demo = [
"bool" => false,
"int" => 1,
"float" => 3.14,
"string" => "hello world",
"array" => [],
"object" => new stdClass(),
"resource" => tmpfile(),
"null" => null,
];
// var_export
$debug_export = var_export($demo, true);
// var_dump (captured using output buffering)
ob_start();
var_dump($demo);
$debug_dump = ob_get_clean();
// print_r (also returns a string if second param is true)
$debug_printr = print_r($demo, true);
Example Outputs:
1. var_export
array (
'bool' => false,
'int' => 1,
'float' => 3.1400000000000001,
'string' => 'hello world',
'array' =>
array (
),
'object' =>
stdClass::__set_state(array(
)),
'resource' => NULL,
'null' => NULL,
)
2.var_dump
array(8) {
[“bool”]=>
bool(false)
[“int”]=>
int(1)
[“float”]=>
float(3.14)
[“string”]=>
string(11) “hello world”
[“array”]=>
array(0) {
}
[“object”]=>
object(stdClass)#1 (0) {
}
[“resource”]=>
resource(4) of type (stream)
[“null”]=>
NULL
}
3. print_r
Array
(
[bool] =>
[int] => 1
[float] => 3.14
[string] => hello world
[array] => Array
(
)
[object] => stdClass Object
(
)
[resource] => Resource id #4
[null] =>
)
Caveat:
var_export cannot handle circular references. For example:
$circular = [];
$circular['self'] =& $circular;
var_export($circular);
⚠️ Produces:
Warning: var_export does not handle circular references
array (
'self' =>
array (
'self' => NULL,
),
)
Meanwhile, var_dump and print_r will show *RECURSION* safely.