Getting PHP’s print_r Function To Return A String
PHP’s print_r function is invaluable. It prints a human-readable string representation of a variable.
It’s one of the most useful debugging features I’ve seen in any language.
I like it so much that I’ve actually written print_r mimic functions for other languages.
By default, print_r literally prints a variable to the screen. Sometimes it’s useful to have that info not printed though. For instance, you might want to include the print_r result in an email, or an error log, or in a special debugging frame.
Fortunately, print_r has this functionality built in – the function accepts an optional second argument that specifies whether you want the data printed or returned as a string.
To have print_r return the data as a string, include the second argument “true”:
$message = print_r($myObject,true);
If you’re doing anything programmatic with the output, you may want to consider using var_export instead. This function is largely identical to print_r, except that its output is machine parsable rather than human readable. The usage is identical to print_r.
$message = var_export($myObject,true);
All without using ob_start. Nice!


April 12th, 2010 at 9:10 am
Thanx for this post :D
Couldn’t find it anywhere else..
January 14th, 2011 at 10:32 am
I’ve seen print_r with a second argument of 1 – ie
print_r($students, 1); does the one represent another form of true, by virtue that it’s a value and therefore to php true? That’s the only way I can fathom it.
January 14th, 2011 at 10:51 am
Yes, Simon, 1 (or any other non-zero number) always means true, while 0 always means false.