Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get the output of var_dump() for better legibility
<?php
/**
* Get the output of var_dump() for better legibility.
*
* @param mixed $arg1..N
*/
function getVarDump() {
$output = array();
foreach (func_get_args() as $arg) {
ob_start();
var_dump($arg);
$output[] = rtrim(preg_replace(
array(
'/\]=>\n\s*/m',
"/^(\\s*'.*' =>)\\n\\s*/m",
'/\{\n\s*\}/',
'/\[\n\s*\]/'
),
array(
'] => ',
'$1 ',
'{ }',
'[ ]',
),
ob_get_clean()),
"\n")
;
}
return implode(', ', $output);
}
/**
* Format the output of var_dump() for better legibility.
*
* @param mixed $arg1..N
*/
function varDump() {
echo call_user_func_array('getVarDump', func_get_args()), PHP_EOL;
}
/**
* Like varDump(), but with the filename and line number prepended.
*
* @param mixed $arg1..N
*/
function varDebug() {
$stack = debug_backtrace();
if (isset($stack[0]['file'])) {
static $useColor;
if (!isset($useColor)) {
$useColor = php_sapi_name() === 'cli' && posix_isatty(STDOUT) && strpos(getenv('TERM'), 'xterm') === 0;
}
static $cwd;
if (!isset($pwd)) {
$cwd = getcwd();
if ($cwd !== false) {
$cwd = rtrim($cwd, '/');
}
}
echo '[';
if ($useColor) {
echo "\033[33m";
}
$file = $cwd && strpos($stack[0]['file'], $cwd) === 0
? str_replace("$cwd/", '', $stack[0]['file'])
: $stack[0]['file'];
echo $file;
if (isset($stack[0]['line'])) {
echo ':' . $stack[0]['line'];
}
if ($useColor) {
echo "\033[0m";
}
echo '] ';
}
echo call_user_func_array('getVarDump', func_get_args()), PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment