Both var_dump and print_r can print php variables in detail. What is the difference between print_r and var_dump?
print_r displays less information than var_dump, thus more concise. print_r only shows the “Array” and “Object” types while var_dump shows all data types such as int, string, etc. var_dump shows the number of members in an array and the number of properties in an object, while print_r does not. For strings, var_dump also shows the number of characters in them but print_r does not. So, to debug complex data types, it is better to use print_r as its output is less disturbing.
Before you use print_r or var_dump to display the content of variables, you should know the correct way to use them. Simply using “var_dump($var);” or “print_r($var)” is not enough as the output will be a mess in the browser because there is no line-break in the output. This is not because print_r and var_dump do not output line-breaks to make the output more readable, but the browser displays line-breaks as spaces. The correct way to use print_r and var_dump is:
echo "<pre>"; print_r($a);echo "</pre>"; echo "<pre>"; var_dump($a);echo "</pre>";
With the <pre> tag, the content of a variable will be displayed on multiple lines. I learned this in a hard way. For many years, I wonder why php does not provide a pretty printer until I saw this post. Even the answer is right there in the post, you still need to be careful enough to find it. Both print_r and var_dump can display the content of objects and arrays. The following is how it looks for objects:
//print_r
A Object
(
[a] => 123
[b] => abc
)
//var_dump
object(A)#1 (2) {
["a"]=>
int(123)
["b"]=>
string(3) "abc"
}
The following is what it looks for arrays:
//print_r
Array
(
[0] => 123
[abc] => 456
[789] => def
)
//var_dump
array(3) {
[0]=>
int(123)
["abc"]=>
int(456)
[789]=>
string(3) "def"
}
Another difference between print_r and var_dump lies in their return value. va_dump has no return value(or returns void) while print_r does have a return value. Usually, print_r returns true. But print_r can take two parameters. If you only provide one parameter, the second parameter is defaulted to false. If you set the second parameter of print_r to true, print_r will not output/display the content of the first parameter, but return the formatted string of the content of the first parameter as a string. Now, you should understand why the following code is wrong:
echo "<pre>".print_r($var)."</pre>";
This will display the content of $var before “<pre>1</prev>”. The correct code is:
echo "<pre>".print_r($var,true)."</pre>";
With the second parameter set to true, print_r displays nothing, and “echo” displays everything.