note 101743 added to function.print-r

From: Date: Sat, 08 Jan 2011 17:31:41 +0000
Subject: note 101743 added to function.print-r
Groups: php.notes 
Request: Send a blank email to php-notes+get-175540@lists.php.net to get a copy of this message
This function removes clutter from print_r's output. I use it instead of print_r now. Here is an example: <?PHP $data = array( "mode" => "sets", "sets" => array( 123, 456, 789 ), "etc" => array( "letters" => array( "a", "b" ), "pie", "sharks" ) ); print_r($data); /* Array ( [mode] => sets [sets] => Array ( [0] => 123 [1] => 456 [2] => 789 ) [etc] => Array ( [letters] => Array ( [0] => a [1] => b ) [0] => pie [1] => sharks ) ) */ neat_r($data); /* mode: sets sets: 123 456 789 etc: letters: a b pie sharks */ ?> Here is the function: <?PHP /* neat_r works like print_r but with much less visual clutter. By Jake Lodwick. Copy freely. */ function neat_r($arr, $return = false) { $out = array(); $oldtab = " "; $newtab = " "; $lines = explode("\n", print_r($arr, true)); foreach ($lines as $line) { //remove numeric indexes like "[0] =>" unless the value is an array if (substr($line, -5) != "Array") { $line = preg_replace("/^(\s*)\[[0-9]+\] => /", "$1", $line, 1); } //garbage symbols foreach (array( "Array" => "", "[" => "", "]" => "", " =>" => ":", ) as $old => $new) { $out = str_replace($old, $new, $out); } //garbage lines if (in_array(trim($line), array("Array", "(", ")", ""))) continue; //indents $indent = ""; $indents = floor((substr_count($line, $oldtab) - 1) / 2); if ($indents > 0) { for ($i = 0; $i < $indents; $i++) { $indent .= $newtab; } } $out[] = $indent . trim($line); } $out = implode("\n", $out) . "\n"; if ($return == true) return $out; echo $out; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 71.167.107.143 ---- Manual Page -- http://www.php.net/manual/en/function.print-r.php Edit -- https://master.php.net/note/edit/101743 Del: integrated -- https://master.php.net/note/delete/101743/integrated Del: useless -- https://master.php.net/note/delete/101743/useless Del: bad code -- https://master.php.net/note/delete/101743/bad+code Del: spam -- https://master.php.net/note/delete/101743/spam Del: non-english -- https://master.php.net/note/delete/101743/non-english Del: in docs -- https://master.php.net/note/delete/101743/in+docs Del: other reasons-- https://master.php.net/note/delete/101743 Reject -- https://master.php.net/note/reject/101743 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#175540) next »