For example suppose you have the following array:
$array = array(); $array['brand']['AE']['shirts']['orange shirt']=1; $array['brand']['AE']['shirts']['black shirt']=1; $array['brand']['Banana Republic']['shirts']['white shirt']=1; $array['brand']['Calvin Klein']['shirts']['blue shirt']=1; $array['brand']['Calvin Klein']['shirts']['red shirt']=1; $array['brand']['Calvin Klein']['shirts']['grey shirt']=1;If I call print_r() with this array I'll see the following in a web browser:
Array ( [brand] => Array ( [AE] => Array ( [shirts] => Array ( [orange shirt] => 1 [black shirt] => 1 ) ) [Banana Republic] => Array ( [shirts] => Array ( [white shirt] => 1 ) ) [Calvin Klein] => Array ( [shirts] => Array ( [blue shirt] => 1 [red shirt] => 1 [grey shirt] => 1 ) ) ) )
This presentation SUCKS! I'd like to see hierarchy of data reflected nicely in the HTML! If no such built in PHP functions exist how do you print human readable information about an array in a readable format in an HTML page?
Solution
While there is no internal PHP function to print an array's contents in a nice, HTML formatted way, you can simply utilize the <pre> HTML tag! The idea is simple: The <pre> tag preserves the spaces within the tag in the HTML presentation and therefore you'll see the hierarchy rendered in HTML!
Here is a custom function I created to do this:
function printArrayInHtml($array) { echo "<pre>\n"; print_r($array); echo "</pre>"; }Call printArrayInHtml() and you'll see the following rendered result in a web browser:
Array ( [brand] => Array ( [AE] => Array ( [shirts] => Array ( [orange shirt] => 1 [black shirt] => 1 ) ) [Banana Republic] => Array ( [shirts] => Array ( [white shirt] => 1 ) ) [Calvin Klein] => Array ( [shirts] => Array ( [blue shirt] => 1 [red shirt] => 1 [grey shirt] => 1 ) ) ) )Easy right? Questions? Let me know!