note 96914 modified in ref.array by danbrown
| From: | danbrown@php.net | Date: | Tue, 23 Mar 2010 14:39:42 +0000 |
| Subject: | note 96914 modified in ref.array by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-167316@lists.php.net to get a copy of this message | ||
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum
depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like
so:
<?php
egvaluetostring($value) //no max depth, or
egvaluetostring($value, $max_depth) //max depth set
function egvaluetostring($value, $max_depth, $key = NULL, $depth = 0, $refChain = array()) {
if($depth > 0)
$tab = str_repeat("\t", $depth);
$text .= $tab . ($key !== NULL ? $key . " => " : "");
if (is_array($value) || is_object($value)) {
$recursion = FALSE;
if (is_object($value)) {
foreach ($refChain as $refVal) {
if ($refVal === $value) {
$recursion = TRUE;
break;
}
}
array_push($refChain, $value);
}
$text .= (is_array($value) ? "array" : "object") . " ( ";
if ($recursion) {
$text .= "*RECURSION* ";
}
elseif (isset($max_depth) && $depth >= $max_depth) {
$text .= "*MAX DEPTH REACHED* ";
}
else {
if (!empty($value)) {
$text .= "\n";
foreach ($value as $child_key => $child_value) {
$text .= egvaluetostring($child_value, $max_depth, (is_array($value) ? "[" :
"") . $child_key . (is_array($value) ? "]" : ""), $depth+1, $refChain)
. ",\n";
}
$text .= "\n" . $tab;
}
}
$text .= ")";
if (is_object($value)) {
array_pop($refChain);
}
}
else {
$text .= "$value";
}
return $text;
}
?>
--was--
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum
depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like
so:
<?php
egvaluetostring($value) //no max depth, or
egvaluetostring($value, $max_depth) //max depth set
?>
<?php
function egvaluetostring($value, $max_depth, $key = NULL, $depth = 0, $refChain = array()) {
if($depth > 0)
$tab = str_repeat("\t", $depth);
$text .= $tab . ($key !== NULL ? $key . " => " : "");
if (is_array($value) || is_object($value)) {
$recursion = FALSE;
if (is_object($value)) {
foreach ($refChain as $refVal) {
if ($refVal === $value) {
$recursion = TRUE;
break;
}
}
array_push($refChain, $value);
}
$text .= (is_array($value) ? "array" : "object") . " ( ";
if ($recursion) {
$text .= "*RECURSION* ";
}
elseif (isset($max_depth) && $depth >= $max_depth) {
$text .= "*MAX DEPTH REACHED* ";
}
else {
if (!empty($value)) {
$text .= "\n";
foreach ($value as $child_key => $child_value) {
$text .= egvaluetostring($child_value, $max_depth, (is_array($value) ? "[" :
"") . $child_key . (is_array($value) ? "]" : ""), $depth+1, $refChain)
. ",\n";
}
$text .= "\n" . $tab;
}
}
$text .= ")";
if (is_object($value)) {
array_pop($refChain);
}
}
else {
$text .= "$value";
}
return $text;
}
http://php.net/manual/en/ref.array.php