Difference Between var_dump and print_r in PHP
In PHP development, debugging variables is a fundamental task, and
var_dump() and print_r() are the two primary
built-in functions used for this purpose. This article explains the
specific purposes of these functions, how they display data, and when
you should use each one during your web development workflow.
The Purpose of print_r()
The print_r() function is designed to display
information about a variable in a way that is easy for humans to read.
It is most commonly used to inspect the structure of arrays and
objects.
- Human-Readable Format: It presents keys and values of arrays or objects in a clean, indented layout.
- Return as a String: By default,
print_r()outputs the result directly to the browser or console. However, if you passtrueas the second argument, it will return the output as a string instead of printing it (e.g.,$result = print_r($array, true);), which is useful for logging. - Minimalist Output: It does not show data types or value lengths, making the output less cluttered but also less detailed.
The Purpose of var_dump()
The var_dump() function is a more powerful debugging
tool that displays highly detailed, structured information about one or
more expressions. It is the go-to function when you need to know exactly
what a variable contains.
- Detailed Metadata: Unlike
print_r(),var_dump()explicitly outputs the data type (such asstring,int,float,array,object, orboolean) and the length or size of the variable. - Type Differentiation: It is crucial for identifying
subtle bugs, as it clearly distinguishes between
false,null,0, and an empty string""—values that might look identical under simpler output functions. - Multiple Arguments: You can pass multiple variables
into a single
var_dump()call (e.g.,var_dump($a, $b, $c)), and it will output details for all of them. - No Return Value: It always outputs directly to the screen and does not have an option to return the data as a string.
Key Differences at a Glance
| Feature | print_r() |
var_dump() |
|---|---|---|
| Primary Focus | Readability | Technical detail / debugging precision |
| Shows Data Types? | No | Yes (e.g., string(5),
int) |
| Shows String Length? | No | Yes |
| Return Option | Yes (via second parameter) | No |
| Accepts Multiple Variables | No | Yes |
When to Use Which
Use print_r() when you want a quick,
clean look at the contents of an array or object to verify its structure
without getting distracted by data types.
Use var_dump() when you are actively
troubleshooting bugs, verifying boolean conditions (like
true vs false), or checking whether a variable
is unexpectedly null or a string representation of a
number.