Hướng dẫn php print_r new line

When I run the following code:

Show
echo $_POST['zipcode'];

print_r($lookup->query($_POST['zipcode']));

?>

the results are concatenated on one line like so: 10952Array.

How can I get it to display on separate lines, like so:

08701
Array

asked Dec 15, 2011 at 7:10

You might need to add a linebreak:

echo $_POST['zipcode'] . '
';

If you wish to add breaks between print_r() statements:

print_r($latitude); 
echo '
'; print_r($longitude);

answered Dec 15, 2011 at 7:12

spanspan

5,5688 gold badges54 silver badges111 bronze badges

2

to break line with print_r:

echo "
";
    print_r($lookup->query($_POST['zipcode']));
echo "
";

The element will format it with any pre-existing formatting, so \n will turn into a new line, returned lines (when you press return/enter) will also turn into new lines.


https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre

brandito

6878 silver badges19 bronze badges

answered Jun 12, 2017 at 16:08

Hướng dẫn php print_r new line

Sen SokhaSen Sokha

1,68614 silver badges15 bronze badges

1

If this is what your browser displays:

Array ( [locus] => MK611812 [version] => MK611812.1 [id] => 1588040742 )

And this is what you want:

Array
(
    [locus] => MK611812
    [version] => MK611812.1
    [id] => 1588040742
)

the easy solution is to add the the

 format to your code that prints the array:

echo "
";
print_r($final);
echo "
";

answered Jun 14, 2019 at 8:59

Hướng dẫn php print_r new line

charelfcharelf

2,6293 gold badges25 silver badges39 bronze badges

Old question, but I generally include the following function with all of my PHP:

The problem occurs because line breaks are not normally shown in HTML output. The trick is to wrap the output inside a pre element:

function printr($data) {
    echo sprintf('
%s
',print_r($data,true)); }

print_r(…, true) returns the output without (yet) displaying it. From here it is inserted into the string using the printf function.

Hướng dẫn php print_r new line

klewis

6,95914 gold badges56 silver badges97 bronze badges

answered Dec 10, 2018 at 7:16

Hướng dẫn php print_r new line

ManngoManngo

11.9k8 gold badges70 silver badges91 bronze badges

2

Just echo these : echo $_POST['zipcode']."
";

answered Dec 15, 2011 at 7:12

Jigar TankJigar Tank

1,4541 gold badge13 silver badges23 bronze badges

(PHP 4, PHP 5, PHP 7, PHP 8)

print_r Prints human-readable information about a variable

Description

print_r(mixed $value, bool $return = false): string|bool

print_r(), var_dump() and var_export() will also show protected and private properties of objects. Static class members will not be shown.

Parameters

value

The expression to be printed.

return

If you would like to capture the output of print_r(), use the return parameter. When this parameter is set to true, print_r() will return the information rather than print it.

Return Values

If given a string, int or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects.

When the return parameter is true, this function will return a string. Otherwise, the return value is true.

Examples

Example #1 print_r() example


$a = array ('a' => 'apple''b' => 'banana''c' => array ('x''y''z'));
print_r ($a);
?>

The above example will output:

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

Example #2 return parameter example

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

Notes

Note:

When the return parameter is used, this function uses internal output buffering prior to PHP 7.1.0, so it cannot be used inside an ob_start() callback function.

See Also

  • ob_start() - Turn on output buffering
  • var_dump() - Dumps information about a variable
  • var_export() - Outputs or returns a parsable string representation of a variable

liamtoh6 at hotmail dot com

12 years ago

I add this function to the global scope on just about every project I do, it makes reading the output of print_r() in a browser infinitely easier.

function print_r2($val){
        echo
'

';
       
print_r($val);
        echo 
'
';
}
?>

It also makes sense in some cases to add an if statement to only display the output in certain scenarios, such as:

if(debug==true)
if($_SERVER['REMOTE_ADDR'] == '127.0.0.1')

simivar at gmail dot com

5 years ago

I've fixed function wrote by Matt to reverse print_r - it had problems with null values. Created a GIST for that too so please add any future fixes in there instead of this comment section:
https://gist.github.com/simivar/037b13a9bbd53ae5a092d8f6d9828bc3

/**
  * Matt: core
  * Trixor: object handling
  * lech: Windows suppport
  * simivar: null support
  *
  * @see http://php.net/manual/en/function.print-r.php
  **/
function print_r_reverse($input) {
       
$lines = preg_split('#\r?\n#', trim($input));
        if (
trim($lines[ 0 ]) != 'Array' && trim($lines[ 0 ] != 'stdClass Object')) {
           
// bottomed out to something that isn't an array or object
           
if ($input === '') {
                return
null;
            }

                        return

$input;
        } else {
           
// this is an array or object, lets parse it
           
$match = array();
            if (
preg_match("/(\s{5,})\(/", $lines[ 1 ], $match)) {
               
// this is a tested array/recursive call to this function
                // take a set of spaces off the beginning
               
$spaces = $match[ 1 ];
               
$spaces_length = strlen($spaces);
               
$lines_total = count($lines);
                for (
$i = 0; $i < $lines_total; $i++) {
                    if (
substr($lines[ $i ], 0, $spaces_length) == $spaces) {
                       
$lines[ $i ] = substr($lines[ $i ], $spaces_length);
                    }
                }
            }
           
$is_object = trim($lines[ 0 ]) == 'stdClass Object';
           
array_shift($lines); // Array
           
array_shift($lines); // (
           
array_pop($lines); // )
           
$input = implode("\n", $lines);
           
$matches = array();
           
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
           
preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $input, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
           
$pos = array();
           
$previous_key = '';
           
$in_length = strlen($input);
           
// store the following in $pos:
            // array with key = key of the parsed array's item
            // value = array(start position in $in, $end position in $in)
           
foreach ($matches as $match) {
               
$key = $match[ 1 ][ 0 ];
               
$start = $match[ 0 ][ 1 ] + strlen($match[ 0 ][ 0 ]);
               
$pos[ $key ] = array($start, $in_length);
                if (
$previous_key != '') {
                   
$pos[ $previous_key ][ 1 ] = $match[ 0 ][ 1 ] - 1;
                }
               
$previous_key = $key;
            }
           
$ret = array();
            foreach (
$pos as $key => $where) {
               
// recursively see if the parsed out value is an array too
               
$ret[ $key ] = print_r_reverse(substr($input, $where[ 0 ], $where[ 1 ] - $where[ 0 ]));
            }

                        return

$is_object ? (object)$ret : $ret;
        }
    }
?>

Matt

13 years ago

Here is another version that parses the print_r() output. I tried the one posted, but I had difficulties with it. I believe it has a problem with nested arrays. This handles nested arrays without issue as far as I can tell.

function print_r_reverse($in) {
   
$lines = explode("\n", trim($in));
    if (
trim($lines[0]) != 'Array') {
       
// bottomed out to something that isn't an array
       
return $in;
    } else {
       
// this is an array, lets parse it
       
if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
           
// this is a tested array/recursive call to this function
            // take a set of spaces off the beginning
           
$spaces = $match[1];
           
$spaces_length = strlen($spaces);
           
$lines_total = count($lines);
            for (
$i = 0; $i < $lines_total; $i++) {
                if (
substr($lines[$i], 0, $spaces_length) == $spaces) {
                   
$lines[$i] = substr($lines[$i], $spaces_length);
                }
            }
        }
       
array_shift($lines); // Array
       
array_shift($lines); // (
       
array_pop($lines); // )
       
$in = implode("\n", $lines);
       
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
       
preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
       
$pos = array();
       
$previous_key = '';
       
$in_length = strlen($in);
       
// store the following in $pos:
        // array with key = key of the parsed array's item
        // value = array(start position in $in, $end position in $in)
       
foreach ($matches as $match) {
           
$key = $match[1][0];
           
$start = $match[0][1] + strlen($match[0][0]);
           
$pos[$key] = array($start, $in_length);
            if (
$previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
           
$previous_key = $key;
        }
       
$ret = array();
        foreach (
$pos as $key => $where) {
           
// recursively see if the parsed out value is an array too
           
$ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
        }
        return
$ret;
    }
}
?>

motin at demomusic dot nu

15 years ago

This works around the hacky nature of print_r in return mode (using output buffering for the return mode to work is hacky...):

/**
  * 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 ? " " : " ";
   
$newline = $html ? "
"
: "\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)

reinder at fake-address dot com

16 years ago

I always use this function in my code, because most of my functions return an Array or Boolean :

function printr ( $object , $name = '' ) {

    print (

'\'' . $name . '\' : ' ) ;

    if (

is_array ( $object ) ) {
        print (
'
' )  ;
       
print_r ( $object ) ;
        print (
'
'
) ;
    } else {
       
var_dump ( $object ) ;
    }

}

?>

( print_r gives no output on FALSE and that can be annoying! )

Bob

13 years ago

Here is a function that formats the output of print_r as a expandable/collapsable tree list using HTML and JavaScript.
function print_r_tree($data)
{
   
// capture the output of print_r
   
$out = print_r($data, true);// replace something like '[element] => (' with ...

', $out);// print the javascript function toggleDisplay() and then the transformed output
   
echo ''."\n$out";
}
?>
Pass it a multidimensional array or object and each sub-array/object will be hidden and replaced by a html link that will toggle its display on and off.
Its quick and dirty, but great for debugging the contents of large arrays and objects.
Note: You'll want to surround the output with

henzeberkheij at gmail dot com

10 years ago

print_r is used for debug purposes. Yet I had some classes where I just wanted the values coming out of the database, not all the other crap. thus i wrote the following function. If your class has an toArray function, that one will be called otherwise it will return the object as is. print_neat_classes_r is the function that should be called!

print_neat_classes_r($array, $return=false){
        return
print_r(self::neat_class_print_r($array), $return);
    }

    function

do_print_r($array, $return=false){
        if(
is_object($array) && method_exists($array, 'toArray')){
            return
$array->toArray();
        }else if(
is_array($array)){
            foreach(
$array as $key=>$obj){
               
$array[$key] = self::do_print_r($obj, $return);
            }
            return
$array;
        }else{
            return
$array;
        }
    }
?>

bart at mediawave dot nl

14 years ago

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.

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:

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*
    )
)

machuidel

11 years ago

The following will output an array in a PHP parsable format:

function serialize_array(&$array, $root = '$root', $depth = 0)
{
       
$items = array();

        foreach(

$array as $key => &$value)
        {
                if(
is_array($value))
                {
                       
serialize_array($value, $root . '[\'' . $key . '\']', $depth + 1);
                }
                else
                {
                       
$items[$key] = $value;
                }
        }

        if(

count($items) > 0)
        {
                echo
$root . ' = array(';$prefix = '';
                foreach(
$items as $key => &$value)
                {
                        echo
$prefix . '\'' . $key . '\' => \'' . addslashes($value) . '\'';
                       
$prefix = ', ';
                }

                echo

');' . "\n";
        }
}
?>

Soaku

5 years ago

posted a function that will echo print_r output with proper new lines in HTML files. He used

 for it to work, but that might not be always the best method to go. For example, it is not valid to place 
 inside 

.

Here is my way to do this:

function print_rbr ($var, $return = false) {
 
$r = nl2br(htmlspecialchars(print_r($var, true)));
  if (
$return) return $r;
  else echo
$r;
}
?>

This function will:

- Place
where newlines are,
- Escape unsecure characters with HTML entities.

thbley at gmail dot com

16 years ago

Here is a print_r that produces xml:
(now you can expand/collapse the nodes in your browser)

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 .= "\n\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 .= "\n";
  return
$output;
}
?>

lech

5 years ago

A slight amendment to Matt's awesome print_r_reverse function (Thank You, a life-saver - data recovery :-) . If the output is copied from a Windows system, the end of lines may include the return character "\r" and so the scalar (string) elements will include a trailing "\r" character that isn't suppose to be there. To resolve, replace the first line in the function with...

= preg_split('#\r?\n#', trim($in)); ?>

This will work for both cases (Linux and Windows).

I include the entire function below for completeness, but all credit to Matt, the original author, Thank You.

//Author: Matt (http://us3.php.net/print_r)
function print_r_reverse($in) {
   
$lines = preg_split('#\r?\n#', trim($in));
    if (
trim($lines[0]) != 'Array') {
       
// bottomed out to something that isn't an array
       
return $in;
    } else {
       
// this is an array, lets parse it
       
if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
           
// this is a tested array/recursive call to this function
            // take a set of spaces off the beginning
           
$spaces = $match[1];
           
$spaces_length = strlen($spaces);
           
$lines_total = count($lines);
            for (
$i = 0; $i < $lines_total; $i++) {
                if (
substr($lines[$i], 0, $spaces_length) == $spaces) {
                   
$lines[$i] = substr($lines[$i], $spaces_length);
                }
            }
        }
       
array_shift($lines); // Array
       
array_shift($lines); // (
       
array_pop($lines); // )
       
$in = implode("\n", $lines);
       
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
       
preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
       
$pos = array();
       
$previous_key = '';
       
$in_length = strlen($in);
       
// store the following in $pos:
        // array with key = key of the parsed array's item
        // value = array(start position in $in, $end position in $in)
       
foreach ($matches as $match) {
           
$key = $match[1][0];
           
$start = $match[0][1] + strlen($match[0][0]);
           
$pos[$key] = array($start, $in_length);
            if (
$previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
           
$previous_key = $key;
        }
       
$ret = array();
        foreach (
$pos as $key => $where) {
           
// recursively see if the parsed out value is an array too
           
$ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
        }
        return
$ret;
    }
}
?>

admin at swivelgames dot com

14 years ago

I was having problems using print_r because I didn't like the fact that if tags where included in the array it would still be parsed by the browsers.

Heres a simple fix for anyone who is having the same problem as I did. This will output your text properly for viewing through the browser instead of the browser's "view source" or CLI.

Script:

     $MyArray

[0]="
My Text
"
;

     echo

"
".htmlspecialchars(print_r($MyArray,true))."
"
;?>

Output:
Array
(
    [0] => <div align='center'>My Text</div>
)

anon at anon dot com

14 years ago

A slight modification to the previous post to allow for arrays containing mutli line strings. haven't fully tested it with everything, but seems to work great for the stuff i've done so far.

function print_r_reverse(&$output)
{
   
$expecting = 0; // 0=nothing in particular, 1=array open paren '(', 2=array element or close paren ')'
   
$lines = explode("\n", $output);
   
$result = null;
   
$topArray = null;
   
$arrayStack = array();
   
$matches = null;
    while (!empty(
$lines) && $result === null)
    {
       
$line = array_shift($lines);
       
$trim = trim($line);
        if (
$trim == 'Array')
        {
            if (
$expecting == 0)
            {
               
$topArray = array();
               
$expecting = 1;
            }
            else
            {
               
trigger_error("Unknown array.");
            }
        }
        else if (
$expecting == 1 && $trim == '(')
        {
           
$expecting = 2;
        }
        else if (
$expecting == 2 && preg_match('/^\[(.+?)\] \=\> (.+)$/', $trim, $matches)) // array element
       
{
            list (
$fullMatch, $key, $element) = $matches;
            if (
trim($element) == 'Array')
            {
               
$topArray[$key] = array();
               
$newTopArray =& $topArray[$key];
               
$arrayStack[] =& $topArray;
               
$topArray =& $newTopArray;
               
$expecting = 1;
            }
            else
            {
               
$topArray[$key] = $element;
            }
        }
        else if (
$expecting == 2 && $trim == ')') // end current array
       
{
            if (empty(
$arrayStack))
            {
               
$result = $topArray;
            }
            else
// pop into parent array
           
{
               
// safe array pop
               
$keys = array_keys($arrayStack);
               
$lastKey = array_pop($keys);
               
$temp =& $arrayStack[$lastKey];
                unset(
$arrayStack[$lastKey]);
               
$topArray =& $temp;
            }
        }
       
// Added this to allow for multi line strings.
   
else if (!empty($trim) && $expecting == 2)
    {
       
// Expecting close parent or element, but got just a string
       
$topArray[$key] .= "\n".$line;
    }
        else if (!empty(
$trim))
        {
           
$result = $line;
        }
    }
$output = implode(n, $lines);
    return
$result;
}
/**
* @param string $output : The output of a multiple print_r calls, separated by newlines
* @return mixed[] : parseable elements of $output
*/
function print_r_reverse_multiple($output)
{
   
$result = array();
    while ((
$reverse = print_r_reverse($output)) !== NULL)
    {
       
$result[] = $reverse;
    }
    return
$result;
}
$output = '
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
            [3] => Array
            (
                [nest] => yes
                [nest2] => Array
                (
                    [nest] => some more
                    asffjaskkd
                )
                [nest3] => o rly?
            )
        )
)

some extra stuff
'

;
var_dump(print_r_reverse($output), $output);?>

This should output

array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  array(4) {
    [0]=>
    string(1) "x"
    [1]=>
    string(1) "y"
    [2]=>
    string(1) "z"
    [3]=>
    array(3) {
      ["nest"]=>
      string(3) "yes"
      ["nest2"]=>
      array(1) {
        ["nest"]=>
        string(40) "some more
                    asffjaskkd"
      }
      ["nest3"]=>
      string(6) "o rly?"
    }
  }
}
string(18) "nsome extra stuffn"

Added:
else if (!empty($trim) && $expecting == 2)
{
    // Expecting close parent or element, but got just a string
    $topArray[$key] .= "\n".$line;
}

Matthew Ruivo (mruivo at gmail)

15 years ago

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!

function return_array($array, $html = false, $level = 0) {
       
$space = $html ? " " : " ";
       
$newline = $html ? "
"
: "\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;
    }
?>

Anonymous

14 years ago

I have written a nice debugging function.
This function handles arrays beautifully.
//Debug variables, $i and $k are for recursive use
function DebugDisplayVar($input, $name = "Debug", $i = "0", $k = array("Error")){
    if(
is_array($input))
    {    foreach (
$input as $i => $value){
           
$temp = $k;
           
$temp[] = $i;
           
DebugDisplayVar($value, $name, $i, $temp);}
    }else{
//if not array
       
echo "$".$name;//[$k]
       
foreach ($k as $i => $value){
            if(
$value !=="Error"){echo "[$value]";}
        }
        echo
" = $input
"
;
}    }
//outputs
Debug[0] = value
Debug
[1] = another value
ect
...?>

warhog at warhog dot net

17 years ago

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:

function print_r_html($arr, $style = "display: none; margin-left: 10px;")
{ static
$i = 0; $i++;
  echo
"\n

$i\" class=\"array_tree\">\n";
  foreach(
$arr as $key => $val)
  { switch (
gettype($val))
    { case
"array":
        echo
";
        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)."

\n"
;
        echo
"
$i\" style=\"$style\">";
        echo
print_r_html($val);
        echo
"
"
;
      break;
      case
"integer":
        echo
"".htmlspecialchars($key)." => ".htmlspecialchars($val)."
";
      break;
      case
"double":
        echo
"".htmlspecialchars($key)." => ".htmlspecialchars($val)."
";
      break;
      case
"boolean":
        echo
"".htmlspecialchars($key)." => ";
        if (
$val)
        { echo
"true"; }
        else
        { echo
"false"; }
        echo 
"
\n"
;
      break;
      case
"string":
        echo
"".htmlspecialchars($key)." => ".htmlspecialchars($val)."
";
      break;
      default:
        echo
"".htmlspecialchars($key)." => ".gettype($val)."
"
;
      break; }
    echo
"\n"; }
  echo
"
\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.

preda dot vlad at yahoo dot com

9 years ago

print_r(), just like var_dump() does NOT cast an object, not even if it has a __toString() method - which is normal.

class A {
    public function
__toString() {
        return
'In class A';
    }
}
$a = new A;
echo
$a; // In class A
print_r($a); // A Object()
// you can simulate the echo by casting it manually
print_r((string)$a);  // In class A

eithed

10 years ago

Bear in mind that print_r actually reserves some memory to do something - so, for example thing like:

function shutdown_handler()
{
   
file_put_contents($_SERVER['DOCUMENT_ROOT']."/log.txt", print_r($_REQUEST, true));
}
ini_set('memory_limit', '1M');
register_shutdown_function("shutdown_handler");$array = array();
while(
true)
   
$array[] = new stdClass();
?>

will just not work. Try using var_export, and presto, everything is fine.

afisher8 at cox dot net

13 years ago

I use this all the time when debugging objects, but when you have a very large object with big arrays of sub-objects, it's easy to get overwhelmed with the large amount of output....sometimes you don't want to see absolutely every sub-object.

I made this function to debug objects while "hiding" sub-objects of certain types.  This also color codes the output for a more readable printout.

function wtf($var, $arrayOfObjectsToHide=null, $fontSize=11)
{
   
$text = print_r($var, true);

    if (

is_array($arrayOfObjectsToHide)) {

            foreach (

$arrayOfObjectsToHide as $objectName) {$searchPattern = '#('.$objectName.' Object\n(\s+)\().*?\n\2\)\n#s';
           
$replace = "$1--> HIDDEN - courtesy of wtf() <--)";
           
$text = preg_replace($searchPattern, $replace, $text);
        }
    }
// color code objects
   
$text = preg_replace('#(\w+)(\s+Object\s+\()#s', '$1$2', $text);
   
// color code object properties
   
$text = preg_replace('#\[(\w+)\:(public|private|protected)\]#', '[$1:$2]', $text);

        echo

'
'.$text.'
'
;
}
// example usage:
wtf($myBigObject, array('NameOfObjectToHide_1', 'NameOfObjectToHide_2'));?>

kurt krueckeberg

13 years ago

This is an alternative for printing arrays. It bolds array values.

function print_array(&$a, $str = "")
{
    if (
$str[0]) {
        echo
"$str =";
    }
    echo
' array( ';
    foreach (
$a as $k => $v) {

        echo

"[$k]".' => ';

        if (

is_array($v)) {
           
print_array($v);
        }
        else {   
               echo
"$a[$k] ";
        }
    }
    echo
')  ';
}
$a1 = array ("apples", "oranges", "pears");
$a2 = array ("potatos", "green beans", "squash");
$a3 = array ("euros", "dollars", "pesos", "dinars");
$test = range(1, 9);
array_push($test, array ("fruit" => $a1, "vegies" => $a2, "money" => $a3));
print_array($test, "test");
?>

Alexander

12 years ago

A simple function to send the output of print_r to firebug.
The script creates a dummy console object with a log method for when firebug is disabled/not available.

function debug ($data) {
    echo
"";
}
?>

Simon Asika

8 years ago

Here is a print_r() clone but support max level limit.

When we want to print a big object, this will help us get a clean dumping data.

/**
* Recrusive print variables and limit by level.
*
* @param   mixed  $data   The variable you want to dump.
* @param   int    $level  The level number to limit recrusive loop.
*
* @return  string  Dumped data.
*
* @author  Simon Asika (asika32764[at]gmail com)
* @date    2013-11-06
*/
function print_r_level($data, $level = 5)
{
    static
$innerLevel = 1;

        static

$tabLevel = 1;

        static

$cache = array();$self = __FUNCTION__;$type       = gettype($data);
   
$tabs       = str_repeat('    ', $tabLevel);
   
$quoteTabes = str_repeat('    ', $tabLevel - 1);$recrusiveType = array('object', 'array');// Recrusive
   
if (in_array($type, $recrusiveType))
    {
       
// If type is object, try to get properties by Reflection.
       
if ($type == 'object')
        {
            if (
in_array($data, $cache))
            {
                return
"\n{$quoteTabes}*RECURSION*\n";
            }
// Cache the data
           
$cache[] = $data;$output     = get_class($data) . ' ' . ucfirst($type);
           
$ref        = new \ReflectionObject($data);
           
$properties = $ref->getProperties();$elements = array();

                        foreach (

$properties as $property)
            {
               
$property->setAccessible(true);$pType = $property->getName();

                                if (

$property->isProtected())
                {
                   
$pType .= ":protected";
                }
                elseif (
$property->isPrivate())
                {
                   
$pType .= ":" . $property->class . ":private";
                }

                                if (

$property->isStatic())
                {
                   
$pType .= ":static";
                }
$elements[$pType] = $property->getValue($data);
            }
        }
       
// If type is array, just retun it's value.
       
elseif ($type == 'array')
        {
           
$output = ucfirst($type);
           
$elements = $data;
        }
// Start dumping datas
       
if ($level == 0 || $innerLevel < $level)
        {
           
// Start recrusive print
           
$output .= "\n{$quoteTabes}(";

                        foreach (

$elements as $key => $element)
            {
               
$output .= "\n{$tabs}[{$key}] => ";// Increment level
               
$tabLevel = $tabLevel + 2;
               
$innerLevel++;$output  .= in_array(gettype($element), $recrusiveType) ? $self($element, $level) : $element;// Decrement level
               
$tabLevel = $tabLevel - 2;
               
$innerLevel--;
            }
$output .= "\n{$quoteTabes})\n";
        }
        else
        {
           
$output .= "\n{$quoteTabes}*MAX LEVEL*\n";
        }
    }
// Clean cache
   
if($innerLevel == 1)
    {
       
$cache = array();
    }

        return

$output;
}
// End function

// TEST ------------------------------------

class testClass
{
    protected
$a = 'aaa';

        private

$b = 'bbb';

        public

$c = array(1, 2, ['a', 'b', 'c'], 4);

        static public

$d = 'ddd';

        static protected

$e = 'eee';
}
$test = new testClass;$test->testClass = $test;

echo

'
' . print_r_level($test, 3) . '
'
;?>

will output
-------------------------------------------------------------

testClass Object
(
    [a:protected] => aaa
    [b:testClass:private] => bbb
    [c] => Array
        (
            [0] => 1
            [1] => 2
            [2] => Array
                *MAX LEVEL*

            [3] => 4
        )

    [d:static] => ddd
    [e:protected:static] => eee
    [testClass] =>
        *RECURSION*

)

schizo do not spamme duckie at gmail dot com

13 years ago

my take on the highlighted markupped debug function:

/**
* print_array()
* Does a var_export of the array and returns it between

 tags

*
* @param mixed $var any input you can think of
* @return string HTML
*/
function print_array($var)
{
   
$input =var_export($var,true);
   
$input = preg_replace("! => \n\W+ array \(!Uims", " => Array ( ", $input);
   
$input = preg_replace("!array \(\W+\),!Uims", "Array ( ),", $input);
    return(
"
".str_replace('>, '>', highlight_string('<'.'?'.$input, true))."
"
);
}
?>

janci

14 years ago

You cannot use print_r(), var_dump() nor var_export() to get static member variables of a class. However, in PHP5 you can use Reflection classes for this:

$reflection

= new ReflectionClass('Static');
print_r($reflection->getStaticProperties());?>

sebasg37 at gmail dot com

13 years ago

If you have to catch the output without showing it at all at first (for example, if you want to append the print_r output to a file), you can do this:

ob_start

();
print_r( $some_array );
$output = ob_get_clean();// if you want to append the print_r output of $some_array to, let's say, log.txt:file_put_contents( 'log.txt', file_get_contents( 'log.txt' ) . $output )?>

Trixor

5 years ago

I've made a small improvement to the print_r_reverse function to also handle objects. Thanks to Matt for making the original.

function print_r_reverse($in) {
 
$lines = explode("\n", trim($in));
  if (
trim($lines[0]) != 'Array' && trim($lines[0] != 'stdClass Object')) {
// bottomed out to something that isn't an array or object
   
return $in;
  } else {
// this is an array or object, lets parse it
   
$match = array();
    if (
preg_match("/(\s{5,})\(/", $lines[1], $match)) {
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
     
$spaces = $match[1];
     
$spaces_length = strlen($spaces);
     
$lines_total = count($lines);
      for (
$i = 0; $i < $lines_total; $i++) {
        if (
substr($lines[$i], 0, $spaces_length) == $spaces) {
         
$lines[$i] = substr($lines[$i], $spaces_length);
        }
      }
    }
   
$is_object = trim($lines[0]) == 'stdClass Object';
   
array_shift($lines); // Array
   
array_shift($lines); // (
   
array_pop($lines); // )
   
$in = implode("\n", $lines);
   
$matches = array();
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
   
preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
   
$pos = array();
   
$previous_key = '';
   
$in_length = strlen($in);
// store the following in $pos:
// array with key = key of the parsed array's item
// value = array(start position in $in, $end position in $in)
   
foreach ($matches as $match) {
     
$key = $match[1][0];
     
$start = $match[0][1] + strlen($match[0][0]);
     
$pos[$key] = array($start, $in_length);
      if (
$previous_key != '') {
       
$pos[$previous_key][1] = $match[0][1] - 1;
      }
     
$previous_key = $key;
    }
   
$ret = array();
    foreach (
$pos as $key => $where) {
// recursively see if the parsed out value is an array too
     
$ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
    }
    return
$is_object ? (object) $ret : $ret;
  }
}
?>

brenden at beagleproductions dot com

14 years ago

Many developers have submitted bugs to the PHP development team with regards to print_r showing protected and private properties of objects (PHP 5).  This is not a bug; sensitive information (ex. database connection object) should be  encapsulated within a private member function of your class.

general at NOSPAMbugfoo dot com

17 years ago

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

Sumit

7 years ago

I prefer to use
printf("

%s
",print_r($_POST, true));
?>

ntd at entidi dot it

7 years ago

Another attempt that tries to overcome the memory blowout when the passed in data has mutual recursion.

function safe_print_r($data, $nesting = 5, $indent = '') {
    if (!
is_object($data) && ! is_array($data)) {
       
var_dump($data);
    } elseif (
$nesting < 0) {
        echo
"** MORE **\n";
    } else {
        echo
ucfirst(gettype($data)) . " (\n";
        foreach ((array)
$data as $k => $v) {
            echo
$indent . "\t[$k] => ";
           
safe_print_r($v, $nesting - 1, "$indent\t");
        }
        echo
"$indent)\n";
    }
}
?>

Soaku

5 years ago

Remember to always htmlspecialchars print_r output, if it can contain html characters.

$array

= array("html");print_r($array); // Invalid output, HTML breaks.
echo htmlspecialchars(print_r($array, true)); // Works and doesn't break the output.
?>

Enthusiastic PHPers

15 years ago

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);

helpful at maybe dot com

14 years ago

Another slight modification to the previous post to allow for empty array elements

added the following lines after the first preg_match block
        } else if ($expecting == 2 && preg_match('/^\[(.+?)\] \=\>$/', $trim, $matches)) { // array element
            // the array element is blank
           
list ($fullMatch, $key) = $matches;
           
$topArray[$key] = $element;
        }
?>

anymix dot services at gmail dot com

5 years ago

// New var export option

function varExp($E,$vE){
    $vE.="=array(";$sep="";
    foreach ($E as $veK => $veV) {
        $vE.=$sep."'$veK'=>'$veV'";$sep=",";
    }
    $vE.=");";
    return $vE;
}

print varExp($I,"\$I");