paul bennett

print_r into a variable

Posted on: February 19, 2007

print_r is a great function. No matter how deeply nested your arrays are, print_r() will dump all the contents out into a neatly indented textual ouput for you to look at.

But what if you need to use the output of print_r() in a variable? Simply set the return flag like so:

$myVar = print_r($bigArray, true);

$myVar now contains the output of print_r().



15 Responses to "print_r into a variable"

Very helpful and straight to the point. Gave me what I wanted in a flash. šŸ˜€

Exactly what I was looking for! Thanks for posting this! Genius, as you said it!


I know this post i so old now, but can you help me with this:

print_r(new MyClass()) prints the class variables and their values.

is there a straight forward way to get the class variables and their values? I want to do name=value pairs given that – very importantly – we do not know the variables in the class in the first place.

this could be due to an unknown base class, or the use of such a function

function addVar($name, $val)
$this->$name = $val;

Hi Jake,

I’ve never needed to do anything like what you’re after, but could you do something like:

$classStructure = print_r($myClass, 1);
and then write a function to parse the data inside $classStructure to extract the variable and / or method names?


alright, guess that’s my only way. thanks! =)

shukran (..means thanks :))


Thanks – I’ve already learnt something today šŸ™‚

Very useful and direct to the point! Thanks!

Googled “print_r to variable”, and voila — you delivered. Thanks!

hi i used print_r($sname) in my php program can u plesae explain the meaning of this.

i write print_r($sname) in my php program.can u please explain the meaning of this.

Haha, this simple! Thank you.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: