PHP: How to print out an array.

This is a small tutorial on how to print out an array in PHP.

As a developer, you will probably have to deal with arrays on a daily basis. Some of them will be simple and straight forward, whereas others will be multidimensional “nightmares” that contain different data types (we’re talking about objects and arrays inside arrays).

To print out and debug a PHP array, you can do two things. You can:

  1. Use print_r or
  2. Use var_dump

Using print_r

If you use print_r by itself, you wll probably get a badly-formatted mess of characters on your screen (if it’s a big array, it will be completely unreadable). However, if you do your print_r inside a <pre> tag, you will get a much nicer display:


$myArray = array(1, 2, 3, 'example' => 7);

echo '<pre>';
echo '</pre>';

If you run the code snippet above, you’ll see the array is printed out on to the screen and that proper spacing and newlines are used:

print_r PHP

Nice, eh?

Using var_dump

OK, but what if you want to see the data types that are in the array? i.e. Is that element an integer or a string? Well, that’s where the function var_dump can come in handy:


//A simple PHP array.
$myArray = array(1, 2, 3, 'example' => 7);

//Print it out with var_dump.

If you have a debugger such as Xdebug installed on your local development machine, then the formatted output of the array will look something like this:

var_dump PHP

Pretty, right?

As you can see, this gives us a lot of information about the structure of our array. It tells us how many elements are in it and it also tells us what type of variables they are!

If you were interested in this article, you might also be interested in printing out an array with recursion.