PHP: Save print_r output into a Variable CodeUnit 10 MAR 2011

print_r() is an extremely useful PHP function that displays the information about just about any type of variable in a way that’s readable by humans. It is particularly essential for the display of arrays, making it often directed towards uncovering those all important system arrays of $_GET, $_POST, $_SERVER and of course, $_SESSION.

However the function by default prints out the information, sometimes not always the most useful of behaviours if you want to return its result as part of a function. However, not all is lost if you know about its second optional parameter, called $return.

$return is defaulted to false, meaning the function follows its default behaviour of printing out the information. However, if you set it to true, print_r() will in fact return what it would have printed as a string, perfect for stuffing into a variable and using elsewhere.

In practice:

$string = print_r($_GET,true);
echo $string;


Related Link:

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

  • Bill Kurtson

    Very helpful! Thanks :)