note 107119 added to function.print-r

From: Date: Mon, 09 Jan 2012 04:21:30 +0000
Subject: note 107119 added to function.print-r
Groups: php.notes 
Request: Send a blank email to php-notes+get-185465@lists.php.net to get a copy of this message
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 ? "&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)) { 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; } ?> ---- Server IP: 192.41.42.26 Probable Submitter: 69.143.136.104 ---- Manual Page -- http://www.php.net/manual/en/function.print-r.php Edit -- https://master.php.net/note/edit/107119 Del: integrated -- https://master.php.net/note/delete/107119/integrated Del: useless -- https://master.php.net/note/delete/107119/useless Del: bad code -- https://master.php.net/note/delete/107119/bad+code Del: spam -- https://master.php.net/note/delete/107119/spam Del: non-english -- https://master.php.net/note/delete/107119/non-english Del: in docs -- https://master.php.net/note/delete/107119/in+docs Del: other reasons-- https://master.php.net/note/delete/107119 Reject -- https://master.php.net/note/reject/107119 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#185465) next »