Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Variable Handling Functions : print_r

print_r

Prints human-readable information about a variable (PHP 4, PHP 5)
mixed print_r ( mixed expression [, bool return] )

Example 2597. print_r() example

<pre>
<?php
$a
= array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

The above example will output:

<pre>
Array
(
   [a] => apple
   [b] => banana
   [c] => Array
       (
           [0] => x
           [1] => y
           [2] => z
       )
)
</pre>

Example 2598. return parameter example

<?php
$b
= array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results now contains output from print_r
?>

Related Examples ( Source code ) » print_r
















Code Examples / Notes » print_r

general

You can't use print_r($var, TRUE) inside a function which is a callback from ob_start() or you get the following error:
Fatal error: print_r(): Cannot use output buffering in output buffering display handlers


enthusiastic phpers

We had an interesting problem dumping an object that
contained embedded HTML. The application makes use
of buffer manipulation functions, so print_r's 2nd argument
wasn't helpful. Here is how we solved the problem:
$object = new ObjectContainingHTML();
$savedbuffercontents = ob_get_clean();
print_r($object);
$print_r_output = ob_get_clean();
ob_start();
echo $savedbuffercontents;
echo htmlentities($print_r_output);


mrasnika

We can all agree that print_r() output is very spartan looking. The debug data needs to be organized better, and presented in a graceful way. In the era of Web 2.0 it is somewhat strange to use plain text to dump information. A DHTML powered informatiion dumping tool will be quite better - like the the open-source alternative of print_r(); -- Krumo (http://krumo.sourceforge.net).
It renders the output using DHTML and collapsible nodes, it's layout is "skinable" and you can change it to fit your aesthetic taste. Krumo makes the output "human-readable" for real :) Plus it is compliant with both PHP4 and PHP5. Plus it detects "reference recursion". Plus you can use it to dump all various sort of data like debug back-traces, the superglobals ($_SERVER, $_ENV, $_REQUEST, $_COOKIE, $_GET, $_POST, $_SESSION), all the included files, all the declared classes, all the declared constants, all your PHP settings, all your php.ini values (if it is readable), all the loaded extensions, all the HTTP request headers, all the declared interfaces (for PHP5), all the file paths from INCLUDE_PATH, all the values of any particular INI file. Additionally it is designed to be easy to use - for example you can disable all the Krumo dumps instead of cleaning your code out of all print_r()'s and var_dump()'s. Anyway, if you check the site (http://krumo.sourceforge.net), you can found a lot of examples, demonstrations, documentation and all sort of helpful information.


motin

This works around the hacky nature of print_r in return mode (using output buffering for the return mode to work is hacky...):
<?php
/**
 * An alternative to print_r that unlike the original does not use output buffering with
 * the return parameter set to true. Thus, Fatal errors that would be the result of print_r
 * in return-mode within ob handlers can be avoided.
 *
 * Comes with an extra parameter to be able to generate html code. If you need a
 * human readable DHTML-based print_r alternative, see http://krumo.sourceforge.net/
 *
 * Support for printing of objects as well as the $return parameter functionality
 * added by Fredrik Wollsén (fredrik dot motin at gmail), to make it work as a drop-in
 * replacement for print_r (Except for that this function does not output
 * paranthesises around element groups... ;) )
 *
 * Based on return_array() By Matthew Ruivo (mruivo at gmail)
 * (http://se2.php.net/manual/en/function.print-r.php#73436)
 */
function obsafe_print_r($var, $return = false, $html = false, $level = 0) {
   $spaces = "";
   $space = $html ? "&nbsp;" : " ";
   $newline = $html ? "<br />" : "\n";
   for ($i = 1; $i <= 6; $i++) {
       $spaces .= $space;
   }
   $tabs = $spaces;
   for ($i = 1; $i <= $level; $i++) {
       $tabs .= $spaces;
   }
   if (is_array($var)) {
       $title = "Array";
   } elseif (is_object($var)) {
       $title = get_class($var)." Object";
   }
   $output = $title . $newline . $newline;
   foreach($var as $key => $value) {
       if (is_array($value) || is_object($value)) {
           $level++;
           $value = obsafe_print_r($value, true, $html, $level);
           $level--;
       }
       $output .= $tabs . "[" . $key . "] => " . $value . $newline;
   }
   if ($return) return $output;
     else echo $output;
}
?>
Built on a function earlier posted in these comments as stated in the Doc comment. Cheers! /Fredrik (Motin)


dmitry kochin
Sometimes print_r produces large output, especially when the data hierarchy is too deep. It is very difficult to analyze the dump about 1Mb length.
It would be great to have some way to fold arrays and objects and to look deeper into hierarchy only on demand.
Here is the solution. Just pass the print_r output to debug_var function:
debug_var('title', print_r($var, true));
and it will produce nice html with folding option.
<?php
 ob_start();
?>
Locals: Array
(
   [arr] => Array
       (
           [0] => Bon Object
               (
                   [n] => id
                   [v] => 1
                   [dv] =>
                   [dn] =>
               )
       )
   [b] => Bon Object
       (
           [n] => id
           [v] => 1
           [dv] =>
           [dn] =>
       )
   [k] => 0
   [row] => Array
       (
           [aid] => 1
           [bonus] => spell.id: 125;
           [req] =>
           [brcache] =>
           [auto] => 0
       )
   [sp] =>
)
<?php
 $str = ob_get_contents();
 ob_end_clean();
 debug_var('locals', $str);
function debug_var($name,$data)
{
   $captured = preg_split("/\r?\n/",$data);
   print "<script>function toggleDiv(num){
     var span = document.getElementById('d'+num);
     var a = document.getElementById('a'+num);
     var cur = span.style.display;
     if(cur == 'none'){
       a.innerHTML = '-';
       span.style.display = 'inline';
     }else{
       a.innerHTML = '+';
       span.style.display = 'none';
     }
   }</script>";
   print "<b>$name</b>\n";
   print "<pre>\n";
   foreach($captured as $line)
   {
       print debug_colorize_string($line)."\n";
   }
   print "</pre>\n";
}
function next_div($matches)
{
 static $num = 0;
 ++$num;
 return "$matches[1]<a id=a$num href=\"javascript: toggleDiv($num)\">+</a><span id=d$num style=\"display:none\">(";
}
/**
* colorize a string for pretty display
*
* @access private
* @param $string string info to colorize
* @return string HTML colorized
* @global
*/
function debug_colorize_string($string)
{
   $string = preg_replace("/\[(\w*)\]/i", '[<font color="red">$1</font>]', $string);
   $string = preg_replace_callback("/(\s+)\($/", 'next_div', $string);
   $string = preg_replace("/(\s+)\)$/", '$1)</span>', $string);
   /* turn array indexes to red */
   /* turn the word Array blue */
   $string = str_replace('Array','<font color="blue">Array</font>',$string);
   /* turn arrows graygreen */
   $string = str_replace('=>','<font color="#556F55">=></font>',$string);
   return $string;
}
?>
This example uses ideas from this article:
http://www.zend.com/zend/tut/tutorial-DebugLib.php


auditor400

some functions I find useful for debugging.
/**
* dump the object in a base.class.php :: print_r2() fashon
this function is for debugging purposes only (obviously)
@see d2()
@param $obj an array of elements, that may have elements that are also arrays.
@param $color the color of the output (useful, when you need to call this several times,
and you need a certain structure to stand out from the others, or simply to differentiate them)
color-coding stuff is a great wa to work, consider this:
@code
p2($struct,'red');
@endcode
to find the function call, just search "red".
in case you find yourself lost, you can always sue the line numbers, @see $dinfo
@param $dinfo see http://www.php.net/debug_backtrace for nifo on debug info.,
0: no info, 1: function call, 2: full backtrace.
@param $title simple remarks you can put to aid you in development. i.e.
@code
$a=array(1,2,3,5,6)

//this
p2($a,'',0,'the numbers');
//is more meaningful than this:
p2($a);
@code
This is particulary true when dealing with many p2()
It is recomended that you *don't* delete p2()'s calls from your code,
but rather document them:
@code

//insightfull comments about spected output
//p2($a123,'',1,'Items in list')
@endcode
or, if you feel more confortable with logging, use this:
$this->log(gp2($struct)); @see gp2()
You can also use p2() as a call trace: helper
@code
function a(){
b();
}
function b(){
c();
}
function d(){
a();
}
function c(){
p2(1,'',2,'backtrace');
}
d();
@endcode

note the use of p2(1), as a simple backtrace enables, you can use
p2($anything,'',2) to display the log, or p2($anything) to show the call route.
the call route follows the following format:
@ file : function : function_call_line_number -> current_line_number
i.e.
@std.php:filter_link():1222->2142
where current line number is the line where the p2() call is, and "function call number"
is the line where the current function was called from (useful as hell).
--
* */
function p2($obj,$color='black',$dinfo=1,$title=''){
//echo();
$dbg=debug_backtrace();
if($dinfo!=0){
//':'.$dbg[1]['class'].
$dinfo="@".basename($dbg[1]['file']).':'.$dbg[1]['function'].'():'.
$dbg[1]['line'].'->'.$dbg[0]['line']."\n";
}
if($dinfo==2){
$dinfo.=print_r(debug_backtrace(),true);
}
if($color==''){$color='rgb(50,50,200)';}
echo("<h3 style='color:$color'>".$title.'</h3><xmp style="color:'.$color.'">'.
$dinfo.print_r($obj,1)."</xmp>");
}
function gp2($obj,$color='black'){
return("<xmp style='color:$color'>".print_r($obj,1)."</xmp>");
}
/**
* @see d2()
* */
function d2_recursive($obj,$label='',$color='rgb(100,100,100)'){
if(is_array($obj)){
$dx="\n<table style='border:1px solid ".$color."' cellspacing=0 cellpadding=2 width=100%>";
if($label!=''){
$dx.="\n<tr><td style='background-color:".$color.";border:1px solid ".$color.
"' colspan=2>".$label."</td></tr>";
}
foreach($obj as $k=>$v){
$dx.="\n<tr><td style='width:1%;color:white;font-weight:bold;font-family:verdana;".
"font-size:10pt;background-color:".$color.";border:1px solid ".$color."'>".$k
.'</td><td style="border:1px solid '.$color.'">';
$dx.=d2_recursive($v,'',$color)."</td></tr>";
}
$dx.="\n</table>";
}else{
$dx=$obj;
}
return($dx);
}
/** \brief nice html object inspector
* @see p2()
* */
function d2($obj,$label='',$color='black'){
echo("\n<!--DUMP:$label START-->\n".d2_recursive($obj,$label,$color)."\n<!--DUMP END-->\n");
}


nicky dot weber

Print arrays formatted for a browser easily:
<?php
function print_html_r( $aData ) {
   echo nl2br( eregi_replace( " ", " ", print_r( $data, TRUE ) ) );
}
?>


mading25

None of the function to output to HTML was working for me so I had to write something that suited my needs. It's probably super not efficient but, hey it works well for me on a small scale.
function print_r_html($data,$return_data=false)
{
$data = print_r($data,true);
$data = str_replace( " ","&nbsp;", $data);
$data = str_replace( "\r\n","
\r\n", $data);
$data = str_replace( "\r","
\r", $data);
$data = str_replace( "\n","
\n", $data);
if (!$return_data)
echo $data;
else
return $data;
}
Simple, isn't? :)


php

If you need to import an print_R output back to an array you could use this.
This could also be (ab)used to convert a object into a array...
<?php
function object2array($printr) {
$newarray = array();
$a[0] = &$newarray;
if (preg_match_all('/^\s+\[(\w+).*\] => (.*)\n/m', $printr, $match)) {
foreach ($match[0] as $key => $value) {
(int)$tabs = substr_count(substr($value, 0, strpos($value, "[")), "        ");
if ($match[2][$key] == 'Array' || substr($match[2][$key], -6) == 'Object') {
$a[$tabs+1] = &$a[$tabs][$match[1][$key]];
}
else {
$a[$tabs][$match[1][$key]] = $match[2][$key];
}
}
}
return $newarray;
}
?>


sawey @ localdomain

I've seen a lot of tries to give an easy way to output the "print_r" info in a decent way in you favorite browser.
Here's mine:
echo ("<pre>");
print_r("-->here goes your data to output<--");
echo ("<pre>");
I personaly think this is the easyest way.
Grz


sakabako

I've got four functions for printing arrays out in a readable fashion, I hope someone finds them useful.
//prints an array in a HTML table. Top row is the keys.
function table( $array ) {
$array = array_values( $array );

$keys = array_keys( $array[0] );

echo '<table border="1"><tr>';
foreach( $keys as $key ) {
echo '<td>'.$key.'</td>';
}
echo '</tr>';

foreach( $array as $row ) {
echo '<tr>';
foreach( $row as $value ) {
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
echo '</table>';
}
//print_r enclosed in a <pre>, except it will always print something, even if the variable is null, number 0 or false. It also lets you label the dump.
function dump( $var, $label=null ) {
if( $var === '' or $var === null or $var === 0 ) {
var_dump( $var );
return;
}
echo '<pre style="text-align: left; font-size: 10px;">';
if( $label ) {
echo $label."\n";
}
print_r( $var );
echo '</pre>';
}
//This one gives you output you can copy and paste back into your PHP code to recreate the array.
function dump_array( $array, $tabs=1 ) {
$html = "<pre style=\"text-align: left; font-size: 10px;\">array( \n";
foreach( $array as $key => $val ) {
$html .= str_repeat( "\t", $tabs )."'$key' => ";
if( is_array( $val ) ) {
$html .= dump_array( $array, $tabs+1 );
} else {
$html .= "'$val',\n";
}
}
$html .= ')</pre>';
return $html;
}
//just add header( 'content-type: application/vnd.ms-excel' ) and you've got an excel file.
function excel( $array ) {
$array = array_values( $array );

$keys = array_keys( $array[0] );

foreach( $keys as $key ) {
echo $key."\t";
}
echo "\n";

foreach( $array as $row ) {
foreach( $row as $value ) {
echo $value."\t";
}
echo "\n";
}
}


markus

i've been using a similar idea like Sawey's for quite a long time,
but was always disappointed that you don't see the name of the
variable passed to the function (eg calling it many times, you don't
know which value was provided by a certain variable at a certain time).
so i combined sawey's idea with one found on php.net to solve that problem.
for shellscripting the function only uses <pre>-tags when called in the web.
<?php
/* how print_r should be ;) */
function my_r(&$var, $scope=false, $label=false){
 if (is_string($scope) && $label==false) $label=$scope;
 if (!is_array($scope)) $scope = &$GLOBALS;
 $origin = $var;
 $var = $checker = "very_weird_value#".rand()."#isnt_it";
 $vname = false;
 foreach ($scope as $key => $value){
   if ($value === $checker){ $vname = "\$".$key; }
   if (is_array($value) && $key!="GLOBALS"){
     if ($pfad=aver($var,$value)){
       $vname = "\$${key}[\"". implode("\"][\"",$pfad)."\"]";
     }
   }
   if (is_object($value)){
     if ($pfad=aver($var,get_object_vars($value))){
       if (sizeof($pfad)<2) $vname = "\$${key}->".$pfad[0];
       else{
         $vname ="\$${key}->".$pfad[0];
         $vname.="[\"".implode("\"][\"", array_slice($pfad,1))."\"]";
       }
     }
   }
   if ($vname) break;
 }
 $var = $origin;
 if ($_SERVER["SERVER_NAME"] && !isset($_SERVER["TERM"])) echo "<pre>";
 if ($vname){
   echo $vname;
   if ($label) echo " #" . $label . "# ";
   else echo ": ";
 }else{
   if ($label) echo "$label: ";
 }
 print_r($var);
 if ($_SERVER["SERVER_NAME"] && !isset($_SERVER["TERM"])) echo "</pre>";
}
/* this function is needed to check in multidimensional arrays
if the value of interest exists. if yes, the path is returned */
function aver($needle,$haystack) { // array value exists recursive
 foreach($haystack as $key=>$val) {
   if(is_array($val) && $needle != $val && $key != "GLOBALS") {
     if($foo=aver($needle,$val)) return array_merge(array($key),$foo);
   }elseif($val === $needle) return array($key);
 }
 return false;
}
?>


sanya

I find a possibly bug, when I wanted to print the structure of a DOMDocument or a DOMDocumentType object.
print_r() outputs the object type correctly, but the properties are missing.
$doc = $imp->createDocument();
$doc->loadXML($xmlString);
print_r($doc->doctype);
the code outputs:
DOMDocumentType Object
(
)
But the subobjects of $doc->doctype exist.


reinder

I always use this function in my code, because most of my functions return an Array or Boolean :
<?php
function printr ( $object , $name = '' ) {
print ( '\'' . $name . '\' : ' ) ;
if ( is_array ( $object ) ) {
print ( '<pre>' )  ;
print_r ( $object ) ;
print ( '</pre>' ) ;
} else {
var_dump ( $object ) ;
}
}
?>
( print_r gives no output on FALSE and that can be annoying! )


jamin42b

Here's a short function that can export php arrays to javascript arrays.
<?php
function php_to_js($array, $base) {
$js = '';
foreach ($array as $key=>$val) {
if (is_array($val)) {
$js .= php_to_js($val, $base.(is_numeric($key) ? '['.$key.']' : "['".addslashes($key)."']"));
} else {
$js .= $base;
$js .= is_numeric($key) ? '['.$key.']' : "['".addslashes($key)."']";
$js .= ' = ';
$js .= is_numeric($val) ? ''.$val.'' : "'".addslashes($val)."'";
$js .= ";\n";
}
}
return $base." = new Array();\n".$js;
}
?>
Example use:
<?php
$my_array = array('gdsag' => 4, 'hello', array(5, 6));
echo '<script>'.php_to_js($my_array).'</script>';
?>
This would output:
<script>
jsvarname = new Array();
jsvarname['gdsag'] = 4;
jsvarname[0] = 'hello';
jsvarname[1] = new Array();
jsvarname[1][0] = 5;
jsvarname[1][1] = 6;
</script>
Now the array is loaded in the browser as javascript. As you can see, it supports multidimensional arrays too.


bart

Here's a PHP version of print_r which can be tailored to your needs. Shows protected and private properties of objects and detects recursion (for objects only!). Usage:
void u_print_r ( mixed $expression [, array $ignore] )
Use the $ignore parameter to provide an array of property names that shouldn't be followed recursively.
<?php
function u_print_r($subject, $ignore = array(), $depth = 1, $refChain = array())
{
if ($depth > 20) return;
if (is_object($subject)) {
foreach ($refChain as $refVal)
if ($refVal === $subject) {
echo "*RECURSION*\n";
return;
}
array_push($refChain, $subject);
echo get_class($subject) . " Object ( \n";
$subject = (array) $subject;
foreach ($subject as $key => $val)
if (is_array($ignore) && !in_array($key, $ignore, 1)) {
echo str_repeat(" ", $depth * 4) . '[';
if ($key{0} == "\0") {
$keyParts = explode("\0", $key);
echo $keyParts[2] . (($keyParts[1] == '*')  ? ':protected' : ':private');
} else
echo $key;
echo '] => ';
u_print_r($val, $ignore, $depth + 1, $refChain);
}
echo str_repeat(" ", ($depth - 1) * 4) . ")\n";
array_pop($refChain);
} elseif (is_array($subject)) {
echo "Array ( \n";
foreach ($subject as $key => $val)
if (is_array($ignore) && !in_array($key, $ignore, 1)) {
echo str_repeat(" ", $depth * 4) . '[' . $key . '] => ';
u_print_r($val, $ignore, $depth + 1, $refChain);
}
echo str_repeat(" ", ($depth - 1) * 4) . ")\n";
} else
echo $subject . "\n";
}
?>
Example:
<?php
class test {
public $var1 = 'a';
protected $var2 = 'b';
private $var3 = 'c';
protected $array = array('x', 'y', 'z');
}
$test = new test();
$test->recursiveRef = $test;
$test->anotherRecursiveRef->recursiveRef = $test;
$test->dont->follow = 'me';
u_print_r($test, array('dont'));
?>
Will produce:
test Object (
   [var1] => a
   [var2:protected] => b
   [var3:private] => c
   [array:protected] => Array (
       [0] => x
       [1] => y
       [2] => z
   )
   [recursiveRef] => *RECURSION*
   [anotherRecursiveRef] => stdClass Object (
       [recursiveRef] => *RECURSION*
   )
)


thbley

Here is a print_r that produces xml:
(now you can expand/collapse the nodes in your browser)
<?php
header('Content-Type: text/xml; charset=UTF-8');
echo print_r_xml($some_var);
function print_r_xml($arr,$first=true) {
 $output = "";
 if ($first) $output .= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<data>\n";
 foreach($arr as $key => $val) {
   if (is_numeric($key)) $key = "arr_".$key; // <0 is not allowed
   switch (gettype($val)) {
 case "array":
       $output .= "<".htmlspecialchars($key)." type='array' size='".count($val)."'>".
 print_r_xml($val,false)."</".htmlspecialchars($key).">\n"; break;
     case "boolean":
       $output .= "<".htmlspecialchars($key)." type='bool'>".($val?"true":"false").
 "</".htmlspecialchars($key).">\n"; break;
     case "integer":
       $output .= "<".htmlspecialchars($key)." type='integer'>".
 htmlspecialchars($val)."</".htmlspecialchars($key).">\n"; break;
     case "double":
       $output .= "<".htmlspecialchars($key)." type='double'>".
 htmlspecialchars($val)."</".htmlspecialchars($key).">\n"; break;
     case "string":
       $output .= "<".htmlspecialchars($key)." type='string' size='".strlen($val)."'>".
 htmlspecialchars($val)."</".htmlspecialchars($key).">\n"; break;
     default:
       $output .= "<".htmlspecialchars($key)." type='unknown'>".gettype($val).
 "</".htmlspecialchars($key).">\n"; break;
   }
 }
 if ($first) $output .= "</data>\n";
 return $output;
}
 
?>


13-dec-2005 09:00

function print_pre($var){
echo '<pre>';
print_r($var);
echo '</pre>'
}


warhog

For very long arrays I have written a little function which formats an array quite nice and uses javascript for browsing it like a tree. The function is very customizable with the $style parameter.
For me it's of great use for browsing large array's, for example when those are used in language-files in some script and so on. It may even be used in "real" scripts for the "real" front-end, cause the tree can very easily be styled (look at the function or the outputted source and you'll see what i mean).
Here's the function:
<?php
function print_r_html($arr, $style = "display: none; margin-left: 10px;")
{ static $i = 0; $i++;
 echo "\n<div id=\"array_tree_$i\" class=\"array_tree\">\n";
 foreach($arr as $key => $val)
 { switch (gettype($val))
   { case "array":
       echo "<a onclick=\"document.getElementById('";
       echo array_tree_element_$i."').style.display = ";
       echo "document.getElementById('array_tree_element_$i";
       echo "').style.display == 'block' ?";
       echo "'none' : 'block';\"\n";
       echo "name=\"array_tree_link_$i\" href=\"#array_tree_link_$i\">".htmlspecialchars($key)."</a><br />\n";
       echo "<div class=\"array_tree_element_\" id=\"array_tree_element_$i\" style=\"$style\">";
       echo print_r_html($val);
       echo "</div>";
     break;
     case "integer":
       echo "<b>".htmlspecialchars($key)."</b> => <i>".htmlspecialchars($val)."</i><br />";
     break;
     case "double":
       echo "<b>".htmlspecialchars($key)."</b> => <i>".htmlspecialchars($val)."</i><br />";
     break;
     case "boolean":
       echo "<b>".htmlspecialchars($key)."</b> => ";
       if ($val)
       { echo "true"; }
       else
       { echo "false"; }
       echo  "<br />\n";
     break;
     case "string":
       echo "<b>".htmlspecialchars($key)."</b> => <code>".htmlspecialchars($val)."</code><br />";
     break;
     default:
       echo "<b>".htmlspecialchars($key)."</b> => ".gettype($val)."<br />";
     break; }
   echo "\n"; }
 echo "</div>\n"; }
?>
The function as it is now does not support the $return parameter as print_r does and will create an endless loop like print_r did in php-versions < 4.0.3 when there is an element which contains a reference to a variable inside of the array to print out :-/
I've tested it with PHP 5.0.6 and PHP 4.2.3 - no problems except those already mentioned.
please e-mail me if you've got a solution for the problems i've mentioned, i myself are not able to solve them 'cause i don't know how the hell i can find out whether a variable is a reference or not.


matthew ruivo mruivo

For those of you needing to print an array within a buffer callback function, I've created this quick function. It simply returns the array as a readable string rather than printing it. You can even choose whether to return it in normal text-mode or HTML. It's recursive, so multi-dimensial arrays are supported. I hope someone finds this useful!
<?php
function return_array($array, $html = false, $level = 0) {
$space = $html ? "&nbsp;" : " ";
$newline = $html ? "<br />" : "\n";
for ($i = 1; $i <= 6; $i++) {
$spaces .= $space;
}
$tabs = $spaces;
for ($i = 1; $i <= $level; $i++) {
$tabs .= $spaces;
}
$output = "Array" . $newline . $newline;
foreach($array as $key => $value) {
if (is_array($value)) {
$level++;
$value = return_array($value, $html, $level);
$level--;
}
$output .= $tabs . "[" . $key . "] => " . $value . $newline;
}
return $output;
}
?>


markus

Explanation:
The problem with figuring out what value is what key in that variables scope is that several variables might have the same value.  To remedy this, the variable is passed by reference and its value is then modified to a random value to make sure there will be a unique match.  Then we loop through the scope ( semi recursively ) the variable is contained in and when there is a match of our modified value, we can grab the correct key and output the name.
Bugs:
You can see in the 5th Example, that the so-called non-existant variable infact exists ;|, the problem with referenced variables (as used in the my_r function) is, that they have to exist at call-time to reference them. that is why my_r("test") will result in a fatal error. if you have ideas to solve that, don't hesitate to mention them.
Examples:
1.  Use of a variable contained in the global scope (default):
<?php
 $my_global_variable = array("nice", "try", "guybrush");
 my_r($my_global_variable);
/* Outputs:  
$my_global_variable: Array
(
   [0] => nice
   [1] => try
   [2] => guybrush
)
*/
?>
2.  Use of a local variable (in a function):
<?php
function my_local_function()
{
 $my_local_variable = array("nice", "try", "guybrush");
 my_r($my_local_variable,get_defined_vars());
}
my_local_function();
/* Outputs:  
$my_local_variable: Array
(
   [0] => nice
   [1] => try
   [2] => guybrush
)
*/
?>
3.  Use of an object property:
<?php
class myclass{
 public function __constructor(){ // depending on php version ;)
   $this->my_object_property = array("nice", "try", name => array("guybrush"));
 }
 public function myclass(){ // depending on php version ;)
   $this->my_object_property = array("nice", "try", name => array("guybrush"));    
 }
}
$obj = new myclass;
my_r($obj->my_object_property);
/* Outputs:
$obj->my_object_property: Array
(
   [0] => nice
   [1] => try
   [name] => Array
       (
           [0] => guybrush
       )
)
*/
?>
4. Use of a sub-array and an additional label
<?php
$foo=array("nice","try",name => array("guybrush","threapwood"))
my_r($foo["name"],"position 1");
/* Outputs:
$foo["name"] #position 1# Array
(
   [0] => guybrush
   [1] => threapwood
)
*/
?>
5. Use of non existant Variables (standard-behaviour of print_r)
<?php
my_r($foo=array("nice","try","guybrush"));
/* Outputs:
Array
(
   [0] => nice
   [1] => try
   [2] => guybrush
)
*/
?>


ohira atto web. de

Bases on thbley´s sript i use this one to log some actions.
It will return a tabbed like string which you can output or whatever.
Input fields like "Password" will not be shown.
<?php
function print_r_string($arr,$first=true,$tab=0)
{
$output = "";
$tabsign = ($tab) ? str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;',$tab) : '';
if ($first) $output .= "<pre>
\n";
foreach($arr as $key => $val)
{
switch (gettype($val))
{
case "array":
$output .= $tabsign."[".htmlspecialchars($key)."] = array(".count($val).")
\n".$tabsign."(
\n";
$tab++;
$output .= print_r_string($val,false,$tab);
$tab--;
$output .= $tabsign.")
\n";
break;
case "boolean":
$output .= $tabsign."[".htmlspecialchars($key)."] bool = '".($val?"true":"false")."'
\n";
break;
case "integer":
$output .= $tabsign."[".htmlspecialchars($key)."] int = '".htmlspecialchars($val)."'
\n";
break;
case "double":
$output .= $tabsign."[".htmlspecialchars($key)."] double = '".htmlspecialchars($val)."'
\n";
break;
case "string":
$output .= $tabsign."[".htmlspecialchars($key)."] string = '".((stristr($key,'passw')) ? str_repeat('*', strlen($val)) : htmlspecialchars($val))."'
\n";
break;
default:
$output .= $tabsign."[".htmlspecialchars($key)."] unknown = '".htmlspecialchars(gettype($val))."'
\n";
break;
}
}
if ($first) $output .= "</pre>
\n";
return $output;
}
echo print_r_string(array($_POST,$_GET)); // for Example
?>


Change Language


Follow Navioo On Twitter
debug_zval_dump
doubleval
empty
floatval
get_defined_vars
get_resource_type
gettype
import_request_variables
intval
is_array
is_binary
is_bool
is_buffer
is_callable
is_double
is_float
is_int
is_integer
is_long
is_null
is_numeric
is_object
is_real
is_resource
is_scalar
is_string
is_unicode
isset
print_r
serialize
settype
strval
unserialize
unset
var_dump
var_export
eXTReMe Tracker