Array display utility for both Human-readable and PHP code drop-in


/ Published in: PHP
Save to your folder(s)

# function *formatArrayForDisplay*

## parameters:


* **array**
a 1- or 2-dimensional array for output
* **mode**
accepts **human** or **PHP**
* **human** displays using `<pre>` tags and print_r
* **PHP** displays PHP style formatting for creating the same array using a PHP script, useful for unit tests when source data is needed.

## returns:

* **void**, all output is directed through **echo**


Copy this code and paste it in your HTML
  1. function formatArrayForDisplay($array,$mode='human'){
  2. switch($mode){
  3. case 'human':
  4. // outputs array as human-readable:
  5. echo "<pre>" . print_r($array,true) . "</pre>";
  6. break;
  7. case 'PHP':
  8. // outputs array as PHP-ready string:
  9. echo "array(";
  10. $comma = '';
  11. foreach($array as $key=>$value){
  12. echo "$comma ";
  13. if(is_array($value)){
  14. echo "array(";
  15. $comma2 = '';
  16. foreach($value as $key2=>$value2){
  17. echo "$comma2 '$key2'=>'$value2'";
  18. $comma2 = ',';
  19. };
  20. echo ")";
  21. unset($comma2,$key2,$value2);
  22. }else{
  23. echo "'$value'";
  24. }
  25. $comma = ',';
  26. };
  27. echo ");";
  28. unset($comma,$key,$value);
  29. break;
  30. }
  31. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.