How to Echo or Print an Array in PHP
Displaying array contents is a fundamental PHP skill every developer needs. This guide covers professional techniques with AdSense-friendly formatting.
<?php
// Properly formatted array declaration
$dataArray = array(
0 => array('car' => 'BMW', 'color' => 'red'),
1 => array('car' => 'Volvo', 'type' => 'COMMUNITY')
);
// Best methods to display array contents:
echo '<pre>';
print_r($dataArray); // Method 1: print_r with pre tags for readability
echo '</pre>';
?>
Key Differences Between Output Methods
| Method | Output Type | Best For |
|---|---|---|
| print_r() | Human-readable | Debugging PHP arrays |
| var_dump() | Technical details | Seeing data types/sizes |
| json_encode() | JSON format | API responses |
Advanced Array Display Techniques
<?php
// Method 2: var_dump with styling
echo '<style>.php-dump{background:#f5f5f5;padding:10px}</style>';
echo '<div class="php-dump">';
var_dump($dataArray);
echo '</div>';
// Method 3: JSON output
echo '<pre>';
echo json_encode($dataArray, JSON_PRETTY_PRINT);
echo '</pre>';
?>
Common Mistakes to Avoid
- Missing quotes around array keys
- Forgetting <pre> tags causing unreadable output
- Direct echo on arrays (triggers warnings)
When to Use Each Method
- Debugging: print_r() with pre tags
- Development: var_dump() for details
- APIs: json_encode() for web apps
For more PHP array functions, see the official PHP documentation.