Skip to content

Instantly share code, notes, and snippets.

@thomedes
Last active August 29, 2015 13:57
Show Gist options
  • Save thomedes/9572770 to your computer and use it in GitHub Desktop.
Save thomedes/9572770 to your computer and use it in GitHub Desktop.
Javascript PHP's print_r()
//-----------------------------------------------------------------------------
//
// print_r(expression[, _return = false ])
//
// PHP's print_r() implemented in javascript
//
// Usage:
// alert(print_r([111, {a: 33, b: 44}], true))
//
// if _return is true will return string
// else will do document.write()
//
//
// (yes I know, I don't use semicolons)
//
//-----------------------------------------------------------------------------
function print_r(expression, _return, padding)
{
"use strict"
var s
padding = padding || ""
function dump(obj) {
var s = ""
var p
s = padding + "(\n"
for (p in obj) {
s += padding + " [" + p + "] => "
s += print_r(obj[p], true, padding + " ")
s += "\n"
}
s += padding + ")\n"
return s
}
if (expression === null || expression === undefined) {
s = ""
} else if (expression.constructor == Object) {
s = "Object\n" + dump(expression)
} else if (expression.constructor == Array) {
s = "Array\n" + dump(expression)
} else {
s = expression.toString()
}
if (_return)
return s
document.write(s)
}
@thomedes
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment