Here is a javscript version of print_r() i had to throw together recently. I was getting so used to being able to use it with php that I became frustrated there was not a javascript version of the like.

I'm playing with javascript remote scripting to a php server page. (The technique the makes maps.google.com so cool and smooth). And was frustrated that techniques used in my php development were so different from the javascript ones. The JS debugger catches syntax errors, but doesn't help me figure out whats going on. So the relevance of this to PHP, there is some, kinda, alittle.

This works fine for what I need it for. But of course, critique away!

JAVASCRIPT:

function print_r(input, _indent)
{
    var indent       = (typeof(_indent)=='string')?_indent+'    ':'    ';
    var paren_indent = (typeof(_indent)=='string')?_indent+'  ':'';

if ( typeof(input) == 'string' ) {
    var output = "'"+ input +"'\n"
} else if ( typeof(input) == 'boolean' ) {
    var output = (input?'true':'false') +"\n"
} else if ( typeof(input) == 'object' ) {
    var output  = ((input.reverse)?'Array':'Object') +"\n"
    output     += paren_indent + "(\n";
    for ( var i in input ) {
        output += indent + "["+ i +"] => "+ print_r(input[i],indent)
    }
    output += paren_indent + ")\n"
}
return output
}
    19 days later

    Very cool! I made a far more basic version just for printing arrays a while ago but I think I'll be using this one in the future. As we're in the critique forum I guess I should put in my 2c. I've made two changes, firstly the condition on the first two lines of the function doesn't need to be evaluated twice so I moved it into one if. The neatness of my sollution is questionable compared to yours, I personally prefer yours 'coz it looks nicer and the difference in processing is minimal if not negligable. Secondly I changed the elseifs to a switch, this is a change which I would make because you'll be evaluating the condition once rather than potentially three times and, in my opinion it does look neater. Here's my updated but as yet untested rewrite.

    function print_r(input, _indent)
    {
        if(typeof(_indent) == 'string') {
            var indent = _indent + '    ';
            var paren_indent = _indent + '  ';
        } else {
            var indent = '    ';
            var paren_indent = '';
        }
    
    switch(typeof(input)) {
        case 'string':
            var output = "" + input  + "\n";
            break;
        case 'boolean':
            var output = (input ? 'true' : 'false') + "\n";
            break;
        case 'object':
            var output = ((input.reverse) ? 'Array' : 'Object') + "\n";
            for(var i in input) {
                output += indent + "[" + i + "] => " + print_r(input[i], indent);
            }
            output += paren_indent + ")\n";
            break;
    }
    return output;
    }
    
      16 days later

      ah yes, woot. infact you are right.

      It is better to roll the two ()?: into a one ifelse

      and the switch is also a better choice. Since this code was constructed bottom up, and added on to as I went, it seemed easier to do things my way. But looking at the completed code top-down, your changes seem obvious (slap head)

      🙂

      I will also be using your updated version.
      Since we are using a switch, we should have a default option that displays things stright, like a string... as well as a special option for the NULL value... but since null is an object, we can't have it's own switch case 🙁

      <script type="text/javascript">
      
      function print_r(input, _indent)
      {
          if(typeof(_indent) == 'string') {
              var indent = _indent + '    ';
              var paren_indent = _indent + '  ';
          } else {
              var indent = '    ';
              var paren_indent = '';
          }
          switch(typeof(input)) {
              case 'boolean':
                  var output = (input ? 'true' : 'false') + "\n";
                  break;
              case 'object':
                  if ( input===null ) {
                      var output = "null\n";
                      break;
                  }
                  var output = ((input.reverse) ? 'Array' : 'Object') + " (\n";
                  for(var i in input) {
                      output += indent + "[" + i + "] => " + print_r(input[i], indent);
                  }
                  output += paren_indent + ")\n";
                  break;
              case 'number':
              case 'string':
              default:
                  var output = "" + input  + "\n";
          }
          return output;
      }
      
      var bar = new Object()
      bar.foo = 'blue'
      var foo = new Array()
      foo['a'] = 1
      foo['b'] = 2
      var num = 3
      var str = 'I am a string'
      var nul = null
      
      document.write('<pre>');
      document.write( 'foo:'+ print_r(foo) );
      document.write( 'bar:'+ print_r(bar) );
      document.write( 'num:'+ print_r(num) );
      document.write( 'str:'+ print_r(str) );
      document.write( 'nul:'+ print_r(nul) );
      document.write('</pre>');
      
      
      </script>
      

      my output was as follows

      foo:Array (
          [a] => 1
          [b] => 2
      )
      bar:Object (
          [foo] => blue
      )
      num:3
      str:I am a string
      nul:null
      

        Sweet!

        /me tucks it away in his toolbox for later

          2 months later

          Very cool! I could have used this many, many times.

          BTW, call me lazy, but i think php should add a print_p() function 🙂

          function print_p($arr) {
             print("<pre>");
             print_r($arr);
             print("</pre>");
          }

          I use that almost religiously.

            yes, I too also use the same thing. I expect that anyone who uses does debugging enough has come up with something similar. I shortened mine to show() however as it is easier than reaching aaaaaaalll the way across the keyboard to the _ button 🙁

              Write a Reply...