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); 

without using ob_start.

Leave a comment