php var_dump() vs print_r()
Question
What is the difference between var_dump()
and print_r()
in terms of spitting out an array as string?
Accepted Answer
The var_dump
function displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.
The print_r()
displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.
Example:
$obj = (object) array('qualitypoint', 'technologies', 'India');
var_dump($obj)
will display below output in the screen.
object(stdClass)#1 (3) {
[0]=> string(12) "qualitypoint"
[1]=> string(12) "technologies"
[2]=> string(5) "India"
}
And, print_r($obj)
will display below output in the screen.
stdClass Object (
[0] => qualitypoint
[1] => technologies
[2] => India
)
More Info
Read more... Read less...
Generally, print_r( )
output is nicer, more concise and easier to read, aka more human-readable but cannot show data types.
With print_r()
you can also store the output into a variable:
$output = print_r($array, true);
which var_dump()
cannot do. Yet var_dump()
can show data types.
If you're asking when you should use what, I generally use print_r()
for displaying values and var_dump()
for when having issues with variable types.
var_dump
displays structured information about the object / variable. This includes type and values. Like print_r
arrays are recursed through and indented.
print_r
displays human readable information about the values with a format presenting keys and elements for arrays and objects.
The most important thing to notice is var_dump
will output type as well as values while print_r
does not.
Significant differences between var_dump
and print_r
both the functions dumps information about the variable, but var_dump
multiple parameters which will be dumped, where as print_r
can take two parameters out of which first parameter is the variable you want to dump and second is a boolean value.
var_dump
can't return any value it can only dump/print the values where as print_r can return the variable information if we set second parameter of print_r
to true. The returned value of print_r
will be in string format.
The information printed by print_r
is much more in readable format where as var_dump
prints raw values.
print_r
function can be used in many contexts where as var_dump
can be used in debugging purposes mainly since it can't return value.