What is the difference between var_dump
, var_export
and print_r
?
2 Answers
var_dump is for debugging purposes. var_dump
always prints the result.
// var_dump(array('', false, 42, array('42')));
array(4) {
[0]=> string(0) ""
[1]=> bool(false)
[2]=> int(42)
[3]=> array(1) {[0]=>string(2) "42")}
}
print_r is for debugging purposes, too, but does not include the member's type. It's a good idea to use if you know the types of elements in your array, but can be misleading otherwise. print_r
by default prints the result, but allows returning as string instead by using the optional $return
parameter.
Array (
[0] =>
[1] =>
[2] => 42
[3] => Array ([0] => 42)
)
var_export prints valid php code. Useful if you calculated some values and want the results as a constant in another script. Note that var_export
can not handle reference cycles/recursive arrays, whereas var_dump
and print_r
check for these. var_export
by default prints the result, but allows returning as string instead by using the optional $return
parameter.
array (
0 => '',
1 => false,
2 => 42,
3 => array (0 => '42',),
)
Personally, I think var_export
is the best compromise of concise and precise.
-
54Note that
var_export
, due to its nature, will die a horrible recursive death on, well, recursive arrays.print_r
andvar_dump
(though, not perfectly sure about latter, since I don't usually use it) don't have that issue. So don'tvar_export($_GLOBALS);
, for example (which contains itself). :) Commented Feb 18, 2011 at 16:28 -
@ftrotter I always thought the comment would explain that curiosity well, but there you go, added a short note to the answer.– phihagCommented Apr 2, 2013 at 1:47
-
1It should be added that you can make print_r() and var_export() return a string instead of outputting it, while var_dump() can't do it. Also, I don't like var_export() since it's confusing - if you try to export some undefined constant SOMECONST, you'll just get back a text string 'SOMECONST'. So it won't say NULL, 0, "", but it will actually presume it's a string (and I suppose throw a NOTICE too). Commented Jan 17, 2014 at 11:53
-
1var_export is good for safely representing a string, like quote/backslash protection.– dkellnerCommented Oct 6, 2015 at 18:43
-
1Personally I prefer
var_dump
output. Too bad it does not allow returning the output as a string. As such I can relate to @iconoclast's sentiment in the comment above. But having to choosevar_export
overvar_dump
for this use case is acceptable to me. For completeness, note this related feature request. Commented Dec 25, 2016 at 14:07
var_dump
and var_export
relate like this (from the manual)
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.
They differ from print_r
that var_dump
exports more information, like the datatype and the size of the elements.