Home / Return information from PHP print_r instead of displaying it

Return information from PHP print_r instead of displaying it

print_r is a useful PHP function for displaying the values of an array or object when debugging etc. Having been a PHP programmer since the days of PHP 3.x (and not having read the manual page for this function in years) I didn’t realise this function had added the capability to return the information as well as print it from PHP 4.3.0 and only discovered this in the last few days. This post gives a brief overview of PHP’s print_r function.

Let’s say for example you have the following array:

$myarray = array(
  "wd" => "well done",
  "m" => "medium",
  "mr" => "medium rare",
  "r" => "rare"
);

Doing this:

print_r($myarray);

will output this:

Array
(
    [wd] => well done
    [m] => medium
    [mr] => medium rare
    [r] => rare
)

If you want to instead suppress the output and return the array information into a variable (which could be emailed in an error report, for example) set the second optional parameter to print_r to true like so:

$info = print_r($myarray);

The output will now not be displayed and the example output above will instead be stored into the $info variable. This should work for any variable types. The following examples would also store the output from print_r into the $info variable instead of outputting to standard output.

$foo = "bar";
$info = print_r($foo, true);

$info = print_r(some_function_call(), true);

$foo = new some_class();
$info = print_r($foo);

It’s really useful to be able to capture information like this using print_r because it means you can use it to store into error logs or send in an error email, as well as for debugging purposes. I only wish I’d known about the additional parameter when it first became available 🙂