print_r

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

print_r Prints human-readable information about a variable

Опис

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

print_r() displays information about a variable in a way that's readable by humans.

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

Параметри

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.

Значення, що повертаються

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.

Журнал змін

Версія Опис
8.4.0 Return type changed from string|bool to string|true.

Приклади

Приклад #1 print_r() example

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

Приклад #2 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
?>

Примітки

Зауваження:

До PHP 7.1.0, якщо передано аргумент return, ця функція застосовує внутрішній буфер виводу, тож вона не може використовуватись всередині функції зворотнього виклику ob_start().

Прогляньте також

  • ob_start() - Turn on output buffering
  • var_dump() - Виводить інформацію про змінну
  • var_export() - Outputs or returns a parsable string representation of a variable

add a note

User Contributed Notes 16 notes

up
163
liamtoh6 at hotmail dot com
15 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.

<?php
function print_r2($val){
echo
'<pre>';
print_r($val);
echo
'</pre>';
}
?>

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')
up
24
simivar at gmail dot com
7 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

<?php
/**
* 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;
}
}
?>
up
3
Soaku
7 years ago
[email protected] posted a function that will echo print_r output with proper new lines in HTML files. He used <pre> for it to work, but that might not be always the best method to go. For example, it is not valid to place <pre> inside <p>.

Here is my way to do this:

<?php

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

?>

This function will:

- Place <br> where newlines are,
- Escape unsecure characters with HTML entities.
up
10
motin at demomusic dot nu
17 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...):

<?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)
up
1
lech
7 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...

<?php $lines = 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.

<?php
//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 = <