0
0
PhpHow-ToBeginner · 3 min read

How to Use print_r in PHP: Syntax and Examples

Use print_r in PHP to display readable information about arrays or objects. Call print_r($variable) to print the content directly or print_r($variable, true) to return it as a string.
📐

Syntax

The print_r function has this syntax:

  • print_r(mixed $expression, bool $return = false): mixed

- $expression is the variable you want to display (array, object, or other types).

- $return is optional; if true, print_r returns the output as a string instead of printing it.

php
print_r($expression, $return = false);
💻

Example

This example shows how to use print_r to display an array's contents directly and how to capture the output as a string.

php
<?php
$fruits = ['apple', 'banana', 'cherry'];

// Print array directly
print_r($fruits);

echo "\n";

// Capture output as string
$output = print_r($fruits, true);
echo "Captured output:\n" . $output;
?>
Output
Array ( [0] => apple [1] => banana [2] => cherry ) Captured output: Array ( [0] => apple [1] => banana [2] => cherry )
⚠️

Common Pitfalls

Common mistakes when using print_r include:

  • Expecting print_r to format output as JSON or HTML (it prints plain text).
  • Not using the second parameter to capture output when needed.
  • Using print_r on very large or deeply nested arrays without formatting, which can be hard to read.

Always remember print_r is for debugging and simple display, not for production output formatting.

php
<?php
// Wrong: expecting JSON format
print_r(['a' => 1, 'b' => 2]); // prints plain text, not JSON

// Right: use json_encode for JSON output
echo json_encode(['a' => 1, 'b' => 2]);
?>
Output
Array ( [a] => 1 [b] => 2 ) {"a":1,"b":2}
📊

Quick Reference

Summary tips for using print_r:

  • Use print_r($var) to print readable info about arrays or objects.
  • Use print_r($var, true) to get the output as a string.
  • Best for debugging, not for user-facing output.
  • For JSON output, use json_encode instead.

Key Takeaways

Use print_r to display readable information about arrays or objects in PHP.
Set the second parameter to true to capture output as a string instead of printing.
print_r outputs plain text, not formatted JSON or HTML.
Ideal for debugging, not for formatting output for users.
For JSON output, prefer json_encode instead of print_r.