PHP: Save print_r output into a Variable

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;

Nifty.

Related Link: http://php.net/manual/en/function.print-r.php

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in PHP and tagged parameter, print_r, variable. Bookmark the permalink.
    blog comments powered by Disqus