Created
January 8, 2011 17:27
-
-
Save jakelodwick/771005 to your computer and use it in GitHub Desktop.
neat_r, a tidy alternative to print_r (PHP)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?PHP | |
/* | |
neat_r works like print_r but with much less visual clutter. | |
By Jake Lodwick. Copy freely. | |
Example with an array: | |
$data = array( | |
"mode" => "sets", | |
"sets" => array( | |
123, | |
456, | |
789 | |
), | |
"etc" => array( | |
"letters" => array( | |
"a", | |
"b" | |
), | |
"pie", | |
"sharks" | |
) | |
); | |
Result of neat_r($data): | |
mode: sets | |
sets: | |
123 | |
456 | |
789 | |
etc: | |
letters: | |
a | |
b | |
pie | |
sharks | |
Result of 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 | |
) | |
) | |
*/ | |
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; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment