← Back to PHP Course | Chapter 2: Output & Input | Lesson 2 of 8

PHP var_dump & print_r

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
<?php
$value = "0";
var_dump($value);
?>

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
<?php
$fruits = ["apple", "banana", "cherry"];
print_r($fruits);
?>

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
<?php
$data = ["a" => 1, "b" => 2];
$output = print_r($data, true);
file_put_contents('log.txt', $output);
echo $output;
?>

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
<?php
$data = [
    "user" => ["name" => "Alice", "roles" => ["admin", "editor"]]
];
var_dump($data);
?>

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
<?php
class User {
    public $name = "Alice";
    private $password = "secret";
}
var_dump(new User());
?>
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.