How to print arrays in PHP for debugging?

Asked 3 years ago 339 views 1 answer Modified 6 hours ago
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?
shama-naaz
50 reputation

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.                                                    
imran-nadwi
answered 3 years ago
You can use Markdown to format your answer.
Last edited: 3 years ago
Preview: