Skip to content

Instantly share code, notes, and snippets.

@faisalman
Last active September 13, 2021 02:57
Show Gist options
  • Save faisalman/879208 to your computer and use it in GitHub Desktop.
Save faisalman/879208 to your computer and use it in GitHub Desktop.
PHP-like print_r() & var_dump() equivalent for JavaScript
Usage example
==============
-- Consider there is an object:
var obj = { foo: 'foo', bar: { foo: true, bar: null, baz: function(){alert('Hello');}}, qux: [1, 3, 2, 'qwerty', 55], quxx: /^[0-9]/ };
-- Then print_r(obj) or var_dump(obj) will return:
Object
{
foo => 'foo',
bar => Object
{
foo => true,
bar => null,
baz => function (){alert('Hello');}
},
qux => Array
[
0 => 1,
1 => 3,
2 => 2,
3 => 'qwerty',
4 => 55
],
quxx => /^[0-9]/
}
/**
* PHP-like print_r() equivalent for JavaScript Object
*
* @author Faisalman <fyzlman@gmail.com>
* @license http://www.opensource.org/licenses/mit-license.php
* @link http://gist.github.com/879208
*/
var print_r = function (obj, t) {
// define tab spacing
var tab = t || '';
// check if it's array
var isArr = Object.prototype.toString.call(obj) === '[object Array]';
// use {} for object, [] for array
var str = isArr ? ('Array\n' + tab + '[\n') : ('Object\n' + tab + '{\n');
// walk through it's properties
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var val1 = obj[prop];
var val2 = '';
var type = Object.prototype.toString.call(val1);
switch (type) {
// recursive if object/array
case '[object Array]':
case '[object Object]':
val2 = print_r(val1, (tab + '\t'));
break;
case '[object String]':
val2 = '\'' + val1 + '\'';
break;
default:
val2 = val1;
}
str += tab + '\t' + prop + ' => ' + val2 + ',\n';
}
}
// remove extra comma for last property
str = str.substring(0, str.length - 2) + '\n' + tab;
return isArr ? (str + ']') : (str + '}');
};
@faisalman
Copy link
Author

I just found out that there is a project called phpjs at http://phpjs.org , more complete set of PHP-like functions for JavaScript can be found there (including print_r() of course), however my implementation has more simple approach and doesn't need any dependencies.

@unicornist
Copy link

you could just go with JSON.stringify() instead

@ravishankarsm
Copy link

@unicornist : Superb ...Smartest of all the replies .. Thanks for that

@staimanovo
Copy link

staimanovo commented Apr 10, 2016

pure perfection :) thanks for sharing

this is the first try able to print out the "window" object (all other chokes on recursion)

@unicornist: try JSON.stringify() the "window" and see the difference

@tarreislam
Copy link

Nice ´+1

@ankurnarkhede
Copy link

ankurnarkhede commented Feb 12, 2019

You can simply use the NPM package @smartankur4u/vardump

npm install @smartankur4u/vardump --save-dev

Usage:

const vardump = require('@smartankur4u/vardump')

var variable = {
  'data': {
    'stuff': [{
      'onetype': [{
        'id': 1,
        'name': 'John Doe'
      },
        {
          'id': 2,
          'name': 'Don Joeh'
        }
      ]
    }]
  }
}


// print the variable using vardump
vardump(variable)

This will print

object(1) {
    ["data"] => object(1) {
        ["stuff"] => array(1) {
            [0] => object(1) {
                ["onetype"] => array(2) {
                    [0] => object(2) {
                        ["id"] => number(1)
                        ["name"] => string(8) "John Doe"
                    }
                    [1] => object(2) {
                        ["id"] => number(2)
                        ["name"] => string(8) "Don Joeh"
                    }
                }
            }
        }
    }
}

Thank me later!

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