PHP’s print_r equivalent in Javascript

Javascript does not provide any direct implementation to print the contents of an array object. Such an implementation is very useful in debugging. Here is my version of the PHP’s print_r implementation:

/*
* Function to print an associative array/object/hash.
* @param Object a The collection to be printed
* @param String dTab This is used for indentation. Its recommended NOT to pass this variable in the function call.
* @return String ret The string representation of the collection.
* @author Kapil Chhabra
* @blog http://my-experiments-with-it.blogspot.com/
*/

print_r = function(a, dTab) {
//initiate the return variable
var ret = “”;

//the depth tabbing variable helps in indentation
if(!dTab) dTab = “\t”;

//If the input variable is a collection object then iterate
if(typeof(a) == ‘object’){

//foreach implementation in javascript
for(var sub in a) {
var val = a[sub];
ret += “‘” + sub + “‘ =>”;

//incase the value obtained is again a collection
if(typeof(val) == ‘object’) {

//drill it down by calling the print_r function recurrsively
ret += “\n” + dTab + “[" + print_r(val, dTab + "\t") + "]\n” + (dTab.substring(0, (dTab.length-1)));
} else {
ret += ” \”" + val + “\”";
}
}
} else {
//Not a collection
ret = “‘” + a + “‘ is of type ‘” + typeof(a) + “‘, not array/object.”;
}
return ret;
}


The usage is fairly simple.

var ar = [{0: [{'a': 'A'}, {'b': 'B'}]}, {1: 2}];
alert(print_r(ar));
alert(print_r(’x'));

It gives the following output: PHPs print_r equivalent in Javascript
 PHPs print_r equivalent in Javascript

This function has helped me a lot. Hope it helps others as well.

Bookmark this post: technorati PHPs print_r equivalent in Javascript delicious PHPs print_r equivalent in Javascript stumbleupon PHPs print_r equivalent in Javascript digg PHPs print_r equivalent in Javascript facebook PHPs print_r equivalent in Javascript yahoo PHPs print_r equivalent in Javascript google PHPs print_r equivalent in Javascript magnolia PHPs print_r equivalent in Javascript reddit PHPs print_r equivalent in Javascript windowslive PHPs print_r equivalent in Javascript

Tags: ,

Related posts

1 Response to “PHP’s print_r equivalent in Javascript”


  1. 1 Tibor

    Did you consider using JSON? It is also human readable, but it’s native to javascript.

Leave a Reply




/kapil/blog is Digg proof thanks to caching by WP Super Cache!