PHP print_r() Function

PHP

PHP print_r() - Print Variable Information

The print_r() function in PHP is a built-in utility that helps developers quickly inspect the contents of variables in a human-readable format. It is especially useful for debugging arrays, objects, and complex data structures during development. This tutorial will guide you through understanding and using print_r() effectively for variable handling and debugging.

Prerequisites

  • Basic knowledge of PHP programming language
  • Access to a PHP-enabled environment (local server or remote hosting)
  • Familiarity with variables, arrays, and objects in PHP

Setup

To start using print_r(), ensure you have PHP installed on your machine or server. You can run PHP scripts through the command line or via a web server like Apache or Nginx.

What is print_r()?

The print_r() function prints human-readable information about a variable. It provides a formatted display, making it easier to visualize arrays and objects compared to using echo or var_dump().

Syntax

print_r(mixed $expression, bool $return = false): string|bool
  • $expression: The variable you want to print.
  • $return: If set to true, print_r() returns the output as a string instead of printing it directly.

Examples

Example 1: Printing a simple array

<?php
$array = ['apple', 'banana', 'cherry'];
print_r($array);
?>

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
)

Example 2: Printing an associative array

<?php
$user = [
    'name' => 'John',
    'age' => 30,
    'email' => 'john@example.com'
];
print_r($user);
?>

Output:

Array
(
    [name] => John
    [age] => 30
    [email] => john@example.com
)

Example 3: Printing an object

<?php
class Person {
    public $name = 'Alice';
    public $age = 25;
}

$person = new Person();
print_r($person);
?>

Output:

Person Object
(
    [name] => Alice
    [age] => 25
)

Example 4: Capturing print_r() output as a string

<?php
$colors = ['red', 'green', 'blue'];
$output = print_r($colors, true);
echo "<pre>" . $output . "</pre>";
?>

This approach is useful for logging or displaying formatted data inside HTML tags (like <pre>).

Best Practices for Using print_r()

  • Wrap output inside <pre></pre> tags when displaying in a browser to preserve formatting.
  • Use print_r() for quick debugging of arrays and objects, but prefer var_dump() when you want detailed type information.
  • Set the second parameter to true to capture the output as a string if you want to manipulate or log it instead of printing directly.
  • Avoid using print_r() in production environments to prevent accidental information leakage about your system or data structures.

Common Mistakes

  • Not wrapping output with <pre> when printing in HTML, leading to unreadable formatting.
  • Calling print_r() on resources (like database connections), which does not provide useful output.
  • Expecting print_r() to show data types precisely; use var_dump() for detailed type information.
  • Forgetting to set the return parameter to true when trying to assign the output to a variable.

Interview Questions

Junior Level

  • Q1: What is the purpose of the print_r() function in PHP?
    A: To print human-readable information about a variable like arrays or objects to help with debugging.
  • Q2: How do you print an array’s contents using print_r()?
    A: Pass the array to print_r(), e.g., print_r($array);.
  • Q3: What happens when you use print_r() on a string variable?
    A: It simply prints the string without additional formatting.
  • Q4: How do you prevent print_r() from directly outputting its result?
    A: Set the second parameter to true, e.g., print_r($var, true); returns the output as a string.
  • Q5: What is the difference between print_r() and echo?
    A: echo prints strings only, while print_r() prints human-readable information about arrays and objects.

Mid Level

  • Q1: How can you format print_r() output for better readability in a browser?
    A: Wrap the output in <pre></pre> tags.
  • Q2: Can print_r() show data types along with values?
    A: No, for detailed type information, var_dump() is preferred.
  • Q3: When would you use the return value of print_r() instead of printing directly?
    A: When you want to store the output in a string variable or log it.
  • Q4: Is it safe to use print_r() to debug production environments?
    A: Generally no, because it can expose sensitive data.
  • Q5: How does print_r() handle objects internally?
    A: It prints the class name and the public properties in an array-like format.

Senior Level

  • Q1: Explain how PHP internally represents the output generated by print_r() for nested arrays.
    A: print_r() recursively traverses nested arrays and formats them with indentation to reflect hierarchy.
  • Q2: How would you customize the output of print_r() for a specific class?
    A: Implement the magic method __debugInfo() in your class to control what print_r() outputs.
  • Q3: Why might print_r() not output any information when provided a resource variable?
    A: Because resources do not have human-readable content that print_r() can display.
  • Q4: Describe how to safely log print_r() output of complex objects without exposing sensitive data.
    A: Use __debugInfo() to filter sensitive properties and capture output with the return parameter before logging.
  • Q5: How does using print_r() with its second parameter set to true improve performance in large debugging tasks?
    A: It avoids immediate output buffering and allows the developer to selectively output or store the data, reducing unnecessary screen clutter.

FAQ

Q1: Can print_r() print all types of variables?

A: It can print most scalar types, arrays, and objects. However, it does not print resource types meaningfully.

Q2: What is the difference between print_r() and var_dump()?

print_r() prints human-readable output of values and structure, while var_dump() includes more detailed information such as data types and lengths.

Q3: How do I format print_r() output in an HTML page properly?

Wrap the output inside <pre></pre> tags to preserve whitespace and indentation.

Q4: Is it possible to get the output of print_r() as a string?

Yes, set the second parameter to true, e.g., print_r($var, true);.

Q5: Should I use print_r() for production debugging?

No, because it can expose sensitive data and impact performance. Use dedicated logging and debugging tools instead.

Conclusion

The PHP print_r() function is a simple yet powerful tool for printing variable contents, especially arrays and objects, in a readable way. It is widely used for debugging during development. Remember to use it carefully in production environments and prefer detailed alternatives like var_dump() when you need type information. Mastering print_r() will improve your debugging workflow and make inspecting complex variables easier.