note 107119 deleted from function.print-r by danbrown
| From: | danbrown@php.net | Date: | Mon, 09 Jan 2012 18:12:45 +0000 |
| Subject: | note 107119 deleted from function.print-r by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-185477@lists.php.net to get a copy of this message | ||
Note Submitter: ari dot n dot schulman at gmail dot com
----
There is a comment below with an excellent function for print_r that is safe with a returned value
and with output buffering turned on (that is, safe with ob_start, etc). However, the posted function
is not recursion-safe. Recursive references in arrays or objects (such as, most notably, the globals
array) will cause a server crash when the function is invoked. Here is a modified, safe function,
which prints out something similar to what print_r itself would do with recursive variables (except,
again, this is safe to use with output buffering turned on):
<?php
* An alternative to print_r that unlike the original does not use output buffering when
* the return parameter is set to true.
*
* This function is modified from http://us.php.net/manual/en/function.print-r.php#75872.
* Modified by Ari N. Schulman (ari.n.schulman ||A|| gmail).
*/
function obsafe_print_r($var, $return = false, $html = false, $level = 0, &$visitedVars =
array()) {
$spaces = "";
$space = $html ? " " : " ";
$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)) {
if (isset($visitedVars[md5(serialize($value))]))
{
$value = '*RECURSION*';
}
else
{
$visitedVars[md5(serialize($value))] = true;
$level++;
$value = obsafe_print_r($value, true, $html, $level, $visitedVars);
$level--;
}
}
else
{
$value = '('.gettype($value).') '.(is_string($value) ?
'"' : '').$value.(is_string($value) ? '"' : '');
}
$output .= $tabs . "[" . $key . "] => " . $value . $newline;
}
if ($return) return $output;
else echo $output;
}
?>