Skip to content

Instantly share code, notes, and snippets.

@xrogaan
Created July 11, 2010 01:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xrogaan/471196 to your computer and use it in GitHub Desktop.
Save xrogaan/471196 to your computer and use it in GitHub Desktop.
try to print a pretty array
<?php
error_reporting(E_ALL);
define('OBIWANKENOBI', true);
function debug($message) {
if (OBIWANKENOBI) {
if (!is_array($message)) {
printf("DEBUG : %s\n", $message);
} else {
printf("START MESSAGE DEBUG -----------------------\n");
var_dump($message);
printf("- END MESSAGE DEBUG -----------------------\n");
}
}
}
function indent($value, $pad_lenght) {
return implode("\n$pad_lenght",explode("\n", $value));
}
function buildMessageFromArray(array $array, $level=1, $lastlen=0) {
if (empty($array)) {
return '';
}
$level = (int) $level;
$pad_lenght = 0;
$tmplen = 0;
foreach ($array as $key => $value) {
$tmplen = strlen($key);
if ($pad_lenght < $tmplen) {
$pad_lenght = $tmplen;
}
}
unset($tmplen,$key,$value);
$prekey = $llen = '';
$tmp='';
foreach ($array as $key => $value) {
if ($lastlen != 0 && $level != 1) {
$tmpllen = ' ';
for ($i=1; $i<$level; $llen.=$tmpllen,$i++);
$prekey = str_pad($llen, $lastlen, ' ');
$lastlen=0;
}
$key = $prekey . str_pad($key, $pad_lenght, ' ',STR_PAD_LEFT);
if (is_array($value)) {
$value = buildMessageFromArray($value, 1+$level, $pad_lenght);
$tmp.="$key:\n". $value;
} else {
$tmp.="$key: " . indent($value, str_pad('', strlen($key)+2), ' ') . "\n";
}
}
return $tmp;
}
$array = array(
'a' => 'this is a',
'b' => array (
'new' => "array",
'next'=> array(
'new' => 'level
level
level',
'blah' => 'same a new',
),
'same' => "same as next",
'same2' => "yah, same",
),
'c' => "yah c
line yah c
line yah c
line yah c",
'd' => 'finally'
);
echo buildMessageFromArray($array);
echo "\n\n";
print_r($array);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment