Converting PHP print_r() Output to a String Variable
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?
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:
Array (  => one  => two  => three )