How to print arrays in PHP for debugging?
22
I need to display the contents of a PHP array for debugging purposes. I want to see the structure and values clearly formatted.
My array looks like this:
$array = array('red', 'pink', 'blue', 'white');
What are the best methods to print or display array contents in PHP?
1 Answer
28
There are several ways to print arrays in PHP for debugging purposes. Here are the most effective methods:
Method 1: print_r() (Most Common)
<?php
$array = array('red', 'pink', 'blue', 'white');
print_r($array);
?>
Method 2: print_r() with <pre> tags (Better Formatting)
<?php
echo '<pre>';
print_r($array);
echo '</pre>';
?>
Method 3: var_dump() (Detailed Information)
<?php
var_dump($array);
?>
var_dump() shows data types, lengths, and more detailed information about each element.
Method 4: var_export() (Valid PHP Code)
<?php
var_export($array);
?>
var_export() outputs valid PHP code that can be used to recreate the variable.
Method 5: Custom Function for Better Display
<?php
function debug_array($array) {
echo '<pre style="background: #f4f4f4; padding: 10px; border: 1px solid #ddd;">';
print_r($array);
echo '</pre>';
}
debug_array($array);
?>
Recommendation: Use print_r() with <pre> tags for general debugging, and var_dump() when you need detailed type information.