Page 1 of 1

print_r to variable?

Posted: Wed Aug 16, 2006 11:49 pm
by 696020
I use print_r($_SESSION) to print out all the nested arrays in the session. is there a way to create a variable that is a string of what would be printed using print_r?

I basically want to do this:

$variable = print_r($_SESSION);

except obviously that won't work.

Posted: Wed Aug 16, 2006 11:58 pm
by Luke

Code: Select all

function capture_print_r($output){
    ob_start();
    print_r($output);
    return ob_get_clean();
}

Posted: Thu Aug 17, 2006 12:02 am
by daedalus__
3 minutes in the manual:

bool print_r ( mixed expression [, bool return] )

Code: Select all

$output = print_r($var, true);

Posted: Thu Aug 17, 2006 12:03 am
by feyd
uh....

bool print_r ( mixed expression [, bool return] )

Note the second argument.
Note the example on the documentation page.

print_r()

Posted: Thu Aug 17, 2006 12:08 am
by 696020
thanks yall

Posted: Thu Aug 17, 2006 12:19 am
by Luke
FINALLY!! I thought I must have been crazy...

viewtopic.php?t=37033

I coulnt'd remember where I saw the ability to return output rather than output it. I didn't realize it wasn't a function, but an argument of the function I was using... silly me.

Posted: Thu Aug 17, 2006 12:54 am
by dibyendrah

Code: Select all

<?php
session_start();
$HTTP_SESSION_VARS['X'] = 'ABC';
$HTTP_SESSION_VARS['Y'] = 'XYZ';

$output = print_r($_SESSION, true);

//print_r($output);
if(is_array($output)){
	print_r($output);
}else{
	var_dump($output);
}

?>

in the above code I tried to return the array output to the $output varaible instead of outputting the variable. When I do print_r($output) it does the output, but when I check the variable if it is array or not by is_array() it don't check it as array but var_dump shows it as array. What's wrong with this ?

:?

Maybe I am wrong ..

Dibyendra

Posted: Thu Aug 17, 2006 12:55 am
by feyd
it's a string.

Posted: Thu Aug 17, 2006 1:01 am
by dibyendrah
but var_dump($output) shows that it is array and print_r($output) takes param as array.

:)
Dibyendra

Posted: Thu Aug 17, 2006 1:03 am
by daedalus__
string.

print_r

Posted: Thu Aug 17, 2006 1:04 am
by feyd
Note the following from the command line

Code: Select all

[feyd@home]>php -r "$foo['XY'] = 'I am foo.'; $foo['AB'] = 'I am foo, too?'; var_dump(gettype($foo),gettype(print_r($foo, true)));"
string(5) "array"
string(6) "string"

Posted: Thu Aug 17, 2006 1:10 am
by dibyendrah
Thanks feyd for the clear view. I was confused a bit what's going on with this .... Now I am clear. I have not used the print_r to store output but only to debug the code.

Cheers,
Dibyendra