How to display an Array in a readable way in PHP

Jonas Maro
2 min readJan 26, 2022
How to display an Array in a readable way in PHP
Pexels

If you work with PHP, when you want to know the value that, at some point, a variable has, especially when we are debugging the code of a page or project, you simply use one of the different functions that the language itself offers: echo, print,

When you want to know the set of values that an array has, the already defined function print_r is usually used. This function will show us a textual representation of its content.

If you have ever used it, you will have noticed that it is quite cumbersome to review the information that this function shows, since when our array is very large, the information becomes unreadable.

Let’s suppose that we have the following array with different values:

$data = array(‘A’, array(‘B’, ‘C’, array(‘D’, ‘E’)), ‘F’);

After using the function print_r, we get:

print_r($data);//Output
Array ( [0] => A [1] => Array ( [0] => B [1] => C [2] => Array ( [0] => D [1] => E ) ) [2] => F )

This is how our array will be displayed on the screen. After reviewing it for a few seconds, you can see its structure, but for larger arrays or with more complicated structures, the resulting string would be quite difficult to understand.

To avoid this, we are going to make the output of our array more understandable, so, to accomplish this, we are going to indicate to the browser that the code to be displayed is a preformatted code, and we do it with the following line:

echo '<pre>'.print_r($data, true).'</pre>';

The second parameter ‘true’ causes the array not to be displayed directly, but rather to be returned as a text string.

Array
(
[0] => A
[1] => Array
(
[0] => B
[1] => C
[2] => Array
(
[0] => D
[1] => E
)
)[2] => F
)

And this is the way in which the array will be displayed, which is quite different from the previous one, allowing us to easily understand its content.

--

--