PHP var_dump & print_r
In this page:
What is var_dump()?
var_dump() is built for debugging, not for user-facing output — it prints a variable's exact type alongside its value, including string length and array/object structure. That type information is exactly what you need to catch bugs like an unexpected string "0" masquerading as a falsy value.
Example: What is var_dump()?
<?php
$value = "0";
var_dump($value);
?>
Login to try C/C++/Java/PHP code in the editor
What is print_r()?
print_r() favors readability over completeness: it shows an array or object's structure in an indented, human-friendly layout without cluttering the output with type annotations. It's usually the first tool reached for when you just want to eyeball what's inside a variable.
Example: What is print_r()?
<?php
$fruits = ["apple", "banana", "cherry"];
print_r($fruits);
?>
Login to try C/C++/Java/PHP code in the editor
print_r() with Return Parameter
Passing true as print_r()'s second argument suppresses the direct screen output and returns the formatted text as a string instead. That's essential when you want to write the dump to a log file or embed it inside another string rather than printing it immediately.
Example: print_r() with Return Parameter
<?php
$data = ["a" => 1, "b" => 2];
$output = print_r($data, true);
file_put_contents('log.txt', $output);
echo $output;
?>
Login to try C/C++/Java/PHP code in the editor
Debugging Nested Arrays
For deeply nested arrays — an array of arrays of objects, say — both functions recursively expand every level, which is exactly what makes them more useful than a plain echo for inspecting complex data: you see the full shape of the structure, not just a top-level summary.
Example: Debugging Nested Arrays
<?php
$data = [
"user" => ["name" => "Alice", "roles" => ["admin", "editor"]]
];
var_dump($data);
?>
Login to try C/C++/Java/PHP code in the editor
var_dump() on Objects
Run var_dump() on an object and you get its class name plus every property's visibility (public/protected/private) and current value. That visibility detail is unique to var_dump() — print_r() shows the values but not which access level each property has.
Example: var_dump() on Objects
<?php
class User {
public $name = "Alice";
private $password = "secret";
}
var_dump(new User());
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: