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:
```php
$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
```
### Method 2: print_r() with
tags (Better Formatting) ```php '; print_r($array); echo ''; ?> ``` ### Method 3: var_dump() (Detailed Information) ```php ``` `var_dump()` shows data types, lengths, and more detailed information about each element. ### Method 4: var_export() (Valid PHP Code) ```php ``` `var_export()` outputs valid PHP code that can be used to recreate the variable. ### Method 5: Custom Function for Better Display ```php '; print_r($array); echo ''; } debug_array($array); ?> ``` **Recommendation:** Use `print_r()` with `
` tags for general debugging, and `var_dump()` when you need detailed type information.