note 75872 added to function.print-r
| From: | motin at demomusic dot nu | Date: | Tue, 19 Jun 2007 23:01:09 +0000 |
| Subject: | note 75872 added to function.print-r | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-127804@lists.php.net to get a copy of this message | ||
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 ? " " : " ";
$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)
----
Server IP: 212.63.193.10
Probable Submitter: 84.217.86.80
----
Manual Page -- http://www.php.net/manual/en/function.print-r.php
Edit -- https://master.php.net/note/edit/75872
Del: integrated -- https://master.php.net/note/delete/75872/integrated
Del: useless -- https://master.php.net/note/delete/75872/useless
Del: bad code -- https://master.php.net/note/delete/75872/bad+code
Del: spam -- https://master.php.net/note/delete/75872/spam
Del: non-english -- https://master.php.net/note/delete/75872/non-english
Del: in docs -- https://master.php.net/note/delete/75872/in+docs
Del: other reasons-- https://master.php.net/note/delete/75872
Reject -- https://master.php.net/note/reject/75872
Search -- https://master.php.net/manage/user-notes.php