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().

Genius.

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!

Thanks!!

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?

Paul

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

shukran (..means thanks :))

@moos,

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 comment

Archives