Adam Norris

Adam Norris

Front-End Developer

← Back to Blog

How To Pretty Print Arrays in PHP

In PHP you often need to debug an array, but you can’t just echo it out as it contains multiple values. You could use a foreach loop and print out all the variables but this can quickly become complex when working with multidimensional arrays. Is there an easier way to do this?

Using print_r

Luckily PHP has a handy function for situations like this called print_r (see docs). print_r will create a human readable version of a variable. We can just pass in our array as an argument.

/* print_r values from an array */
$someArray = array( 1, 2, array( "a", "b", "c" ) );
print_r($someArray)

You’ll notice that the results aren’t formatted which can make it difficult to read, especially with bigger arrays. To fix this, we can just wrap the print_r function in <pre> tags so it retains its formatting.

/* nicely formatted print_r values from an array */
$someArray = array( 1, 2, array( "a", "b", "c" ) );
echo '<pre>';
print_r($someArray);
echo '</pre>';

Using var_dump

PHP also offers us another handy little function call var_dump (see docs) which not only prints out the information but shows us the variable types being used.

/* returning information with var_dump */
$someArray = array( 1, 2, array( "a", "b", "c" ) );
echo '<pre>';
var_dump($someArray)
echo '</pre>';

Using var_export

Finally, var_export (see docs) can also be used. This is similar to var_dump, with the added bonus that what gets returned is valid PHP code.

/* returning information with print_r */
$someArray = array( 1, 2, array( "a", "b", "c" ) );
echo '<pre>' . var_export($someArray, true) . '</pre>';