print_r

(PHP 4, PHP 5)

print_r --  打印关于变量的易于理解的信息。

描述

bool print_r ( mixed expression [, bool return] )

注: 参数 return 是在 PHP 4.3.0 的时候加上的

print_r() 显示关于一个变量的易于理解的信息。如果给出的是 stringintegerfloat,将打印变量值本身。如果给出的是 array,将会按照一定格式显示键和元素。object 与数组类似。

记住,print_r() 将把数组的指针移到最后边。使用 reset() 可让指针回到开始处。

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

上边的代码将输出:
<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

如果想捕捉 print_r() 的输出,可使用 return 参数。若此参数设为 TRUEprint_r() 将不打印结果(此为默认动作),而是返回其输出。

例子 1. return 参数示例

<?php
    $b
= array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
    
$results = print_r ($b, true); //$results 包含了 print_r 的输出结果
?>

注: 如果想在 PHP 4.3.0 之前的版本中捕捉 print_r() 的输出,可使用输出控制函数

注: 在 PHP 4.0.4 之前的版本中,如果给出的 arrayobject 包含了直接或间接指向自身的引用,print_r() 将永远继续下去。print_r($GLOBALS) 就是一个例子,因为 $GLOBALS 自身即是全局变量,其包含了指向自身的引用。

参见 ob_start()var_dump()var_export()


add a note add a note User Contributed Notes
auditor400 at gmail dot com
02-Nov-2006 11:56
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");
   }
Dmitry Kochin <dco at mail dot ru>
08-Sep-2006 04:20
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
ohira (atto) web. de
13-Apr-2006 10:01
Bases on thbleys 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><br>\n";
   foreach(
$arr as $key => $val)
   {
       switch (
gettype($val))
       {
           case
"array":
              
$output .= $tabsign."[".htmlspecialchars($key)."] = array(".count($val).")<br>\n".$tabsign."(<br>\n";
              
$tab++;
              
$output .= print_r_string($val,false,$tab);
              
$tab--;
              
$output .= $tabsign.")<br>\n";
           break;
           case
"boolean":
              
$output .= $tabsign."[".htmlspecialchars($key)."] bool = '".($val?"true":"false")."'<br>\n";
           break;
           case
"integer":
              
$output .= $tabsign."[".htmlspecialchars($key)."] int = '".htmlspecialchars($val)."'<br>\n";
           break;
           case
"double":
              
$output .= $tabsign."[".htmlspecialchars($key)."] double = '".htmlspecialchars($val)."'<br>\n";
           break;
           case
"string":
              
$output .= $tabsign."[".htmlspecialchars($key)."] string = '".((stristr($key,'passw')) ? str_repeat('*', strlen($val)) : htmlspecialchars($val))."'<br>\n";
           break;
           default:
              
$output .= $tabsign."[".htmlspecialchars($key)."] unknown = '".htmlspecialchars(gettype($val))."'<br>\n";
           break;
       }
   }
   if (
$first) $output .= "</pre><br>\n";
   return
$output;
}

echo
print_r_string(array($_POST,$_GET)); // for Example
?>
sanya at hik dot hu
05-Apr-2006 10:13
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 at fake-address dot com
01-Feb-2006 01:09
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! )
13-Dec-2005 05:00
function print_pre($var){
echo '<pre>';
print_r($var);
echo '</pre>'
}
thbley at gmail dot com
17-Nov-2005 04:10
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;
}
 
?>
jamin42b at gmail dot com
02-Sep-2005 08:52
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.
warhog at warhog dot net
12-Aug-2005 08:01
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.
nicky dot weber at siner dot de
11-Jun-2005 05:13
Print arrays formatted for a browser easily:

<?php
function print_html_r( $aData ) {
   echo
nl2br( eregi_replace( " ", " ", print_r( $data, TRUE ) ) );   
}
?>
general at NOSPAMbugfoo dot com
21-Jan-2005 05:23
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