PHP: View an array in a readable format

View an array in a readable formatIn PHP, an array is an excellent way to hold and manipulate data. But working with arrays with a complex, multidimensional structure or are very long can sometimes be difficult to read and test. Take the following example, the function print_r() can been used to recursively print the contents of an array to the browser:

<?php
 $fruit = array('Orange','Apple','Banana','Mango','Pineapple','Kiwi','Pear','Persimmon','Star Fruit','Melon','Peach','Grape','Strawberry','Raspberry','Gooseberry','Blueberry');
 print_r($fruit);
 ?>

Example output:

Array ( [0] => Orange [1] => Apple [2] => Banana [3] => Mango [4] => Pineapple [5] => Kiwi [6] => Pear [7] => Persimmon [8] => Star Fruit [9] => Melon [10] => Peach [11] => Grape [12] => Strawberry [13] => Raspberry [14] => Gooseberry [15] => Blueberry )

As you can see, this is fairly difficult to follow. Imagine what it would be like reading from a multidimensional array!

<?php
 $fruit = array('Orange',array('Golden Delicious','Granny Smiths', 'Braeburn'),'Banana','Mango','Pineapple','Kiwi','Pear','Persimmon','Star Fruit','Melon','Peach','Grape','Strawberry','Rasberry','Gooseberry','Blueberry');
 print_r($fruit);
 ?>

Example output:

Array ( [0] => Orange [1] => Array ( [0] => Golden Delicious [1] => Granny Smiths [2] => Braeburn ) [2] => Banana [3] => Mango [4] => Pineapple [5] => Kiwi [6] => Pear [7] => Persimmon [8] => Star Fruit [9] => Melon [10] => Peach [11] => Grape [12] => Strawberry [13] => Raspberry [14] => Gooseberry [15] => Blueberry )

Introducing <pre> for arrays

This problem can be easily overcome with the use of the <pre> tag (defines preformatted text). Now you can visualise your array in a readable format.

<?php
$fruit = array('Orange',array('Golden Delicious','Granny Smiths', 'Braeburn'),'Banana','Mango','Pineapple','Kiwi','Pear','Persimmon','Star Fruit','Melon','Peach','Grape','Strawberry','Raspberry','Gooseberry','Blueberry');

echo '<pre>';
 print_r($fruit);
echo '</pre>';
?>

This will output, rather neatly:

Array
(
 [0] => Orange
 [1] => Array
  (
   [0] => Golden Delicious
   [1] => Granny Smiths
   [2] => Braeburn
  )
 [2] => Banana
 [3] => Mango
 [4] => Pineapple
 [5] => Kiwi
 [6] => Pear
 [7] => Persimmon
 [8] => Star Fruit
 [9] => Melon
 [10] => Peach
 [11] => Grape
 [12] => Strawberry
 [13] => Rasberry
 [14] => Gooseberry
 [15] => Blueberry
)

Leave a Reply

Your email address will not be published. Required fields are marked *