Converting PHP print_r() Output to a String Variable

April 4th, 2011 - Posted by Steve Marks to PHP, Web Development.

The PHP function print_r() is great at outputting a variable in a human-readable format. What if we don’t want it to print to the screen however and instead, for example, want to include it’s output in an email?

The Solution

You might be suprised to learn that you don’t need to find another function or do any fancy output buffering to acheive this (I found this out the hard way!). The print_r() function supports a second parameter that, if set as TRUE will store the results to a variable rather than output them. A simple example would be like so:

$myArray = array('one', 'two', 'three');
$myString = print_r($myArray, TRUE);
echo $myString;

The above would then output the following:

	[0] => one
	[1] => two
	[2] => three
Tags: ,
This entry was posted on Monday, April 4th, 2011 at 7:25 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (8)
  1. @evilripper – serialize() does indeed the do a similar thing. I think print_r() is easier to read however, especially when it comes to debugging. Good point though :)

  2. not so nice but it works! thanks :)
    an alternative is serialize().

  3. wilson says:

    thanks so much for your info, really useful.

  4. Thanks a lot – enabling print_r to print to a var or being able to use it in a return statement is _very_ helpful. I used print_r a lot for internal “offline” testing – know i can even use it in my production environment from time to time ;-)

  5. Richie says:

    Thanks that exactly what I needed. A simply TRUE switch! Great work.

  6. Krrish says:

    I also wrote an article on this… Introduction of second parameter is really a good move. Programmers can either use true and false OR 1 and 0.

  7. Ed says:

    I was just about to throw in the towel with the code I was working on and did one last search and came across your post. I can’t believe I didn’t think to use the TRUE parameter. Wasted 2 hours mucking around, but I am totally stoked and very appreciative. Thanks for this hot tip!!!!