Posted By

ianmonge on 09/13/08


Tagged

javascript php printr phpjs


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

SpinZ


Javascript equivalent for PHP's print_r


 / Published in: JavaScript
 

URL: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_print_r/

Description

print_r - Prints human-readable information about a variable

mixed print_r( mixed expression [, bool return] )

print_r() displays information about a variable in a way that's readable by humans. Parameters

* expression

  The expression to be printed.
* return

  If you would like to capture the output of print_r(), use the return parameter. If this parameter is set to TRUE, print_r() will return its output, instead of printing it (which it does by default).

Return Values

If given a string, integer or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects.

  1. function print_r( array, return_val ) {
  2. // http://kevin.vanzonneveld.net
  3. // + original by: Michael White (http://crestidg.com)
  4. // + improved by: Ben Bryan
  5. // * example 1: print_r(1, true);
  6. // * returns 1: 1
  7.  
  8. var output = "", pad_char = " ", pad_val = 4;
  9.  
  10. var formatArray = function (obj, cur_depth, pad_val, pad_char) {
  11. if (cur_depth > 0) {
  12. cur_depth++;
  13. }
  14.  
  15. var base_pad = repeat_char(pad_val*cur_depth, pad_char);
  16. var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
  17. var str = "";
  18.  
  19. if (obj instanceof Array || obj instanceof Object) {
  20. str += "Array\n" + base_pad + "(\n";
  21. for (var key in obj) {
  22. if (obj[key] instanceof Array) {
  23. str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
  24. } else {
  25. str += thick_pad + "["+key+"] => " + obj[key] + "\n";
  26. }
  27. }
  28. str += base_pad + ")\n";
  29. } else if(obj == null || obj == undefined) {
  30. str = '';
  31. } else {
  32. str = obj.toString();
  33. }
  34.  
  35. return str;
  36. };
  37.  
  38. var repeat_char = function (len, pad_char) {
  39. var str = "";
  40. for(var i=0; i < len; i++) {
  41. str += pad_char;
  42. };
  43. return str;
  44. };
  45. output = formatArray(array, 0, pad_val, pad_char);
  46.  
  47. if (return_val !== true) {
  48. document.write("<pre>" + output + "</pre>");
  49. return true;
  50. } else {
  51. return output;
  52. }
  53. }

Report this snippet  

You need to login to post a comment.