(PHP 4, PHP 5)
var_dump — 打印变量的相关信息
此函数显示关于一个或多个表达式的结构信息,包括表达式的类型与值。数组将递归展开值,通过缩进显示其结构。
In PHP 5 all public, private and protected properties of objects will be returned in the output.
expression
你要打印的变量。
没有返回值。
Example #1 var_dump() 例子
<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>
以上例程会输出:
array(3) { [0]=> int(1) [1]=> int(2) [2]=> array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" } }
<?php
$b = 3.1;
$c = true;
var_dump($b, $c);
?>
以上例程会输出:
float(3.1) bool(true)
stlawson *AT* joyfulearthtech *DOT* com (2011-08-10 09:31:37)
<?php
/**
* Better GI than print_r or var_dump -- but, unlike var_dump, you can only dump one variable.
* Added htmlentities on the var content before echo, so you see what is really there, and not the mark-up.
*
* Also, now the output is encased within a div block that sets the background color, font style, and left-justifies it
* so it is not at the mercy of ambient styles.
*
* Inspired from: PHP.net Contributions
* Stolen from: [highstrike at gmail dot com]
* Modified by: stlawson *AT* JoyfulEarthTech *DOT* com
*
* @param mixed $var -- variable to dump
* @param string $var_name -- name of variable (optional) -- displayed in printout making it easier to sort out what variable is what in a complex output
* @param string $indent -- used by internal recursive call (no known external value)
* @param unknown_type $reference -- used by internal recursive call (no known external value)
*/
function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL)
{
$do_dump_indent = "<span style='color:#666666;'>|</span> ";
$reference = $reference.$var_name;
$keyvar = 'the_do_dump_recursion_protection_scheme'; $keyname = 'referenced_object_name';
// So this is always visible and always left justified and readable
echo "<div style='text-align:left; background-color:white; font: 100% monospace; color:black;'>";
if (is_array($var) && isset($var[$keyvar]))
{
$real_var = &$var[$keyvar];
$real_name = &$var[$keyname];
$type = ucfirst(gettype($real_var));
echo "$indent$var_name <span style='color:#666666'>$type</span> = <span style='color:#e87800;'>&$real_name</span><br>";
}
else
{
$var = array($keyvar => $var, $keyname => $reference);
$avar = &$var[$keyvar];
$type = ucfirst(gettype($avar));
if($type == "String") $type_color = "<span style='color:green'>";
elseif($type == "Integer") $type_color = "<span style='color:red'>";
elseif($type == "Double"){ $type_color = "<span style='color:#0099c5'>"; $type = "Float"; }
elseif($type == "Boolean") $type_color = "<span style='color:#92008d'>";
elseif($type == "NULL") $type_color = "<span style='color:black'>";
if(is_array($avar))
{
$count = count($avar);
echo "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:#666666'>$type ($count)</span><br>$indent(<br>";
$keys = array_keys($avar);
foreach($keys as $name)
{
$value = &$avar[$name];
do_dump($value, "['$name']", $indent.$do_dump_indent, $reference);
}
echo "$indent)<br>";
}
elseif(is_object($avar))
{
echo "$indent$var_name <span style='color:#666666'>$type</span><br>$indent(<br>";
foreach($avar as $name=>$value) do_dump($value, "$name", $indent.$do_dump_indent, $reference);
echo "$indent)<br>";
}
elseif(is_int($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".htmlentities($avar)."</span><br>";
elseif(is_string($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color\"".htmlentities($avar)."\"</span><br>";
elseif(is_float($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".htmlentities($avar)."</span><br>";
elseif(is_bool($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".($avar == 1 ? "TRUE":"FALSE")."</span><br>";
elseif(is_null($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> {$type_color}NULL</span><br>";
else echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> ".htmlentities($avar)."<br>";
$var = $var[$keyvar];
}
echo "</div>";
}
?>
kobrasrealm at gmail dot com (2011-06-23 13:28:49)
I wrote this dandy little function for using var_dump() on HTML documents so I don't have to view the source.
<?php
function htmldump($variable, $height="9em") {
echo "<pre style=\"border: 1px solid #000; height: {$height}; overflow: auto; margin: 0.5em;\">";
var_dump($variable);
echo "</pre>\n";
}
?>
You can pass arguments like this:
<?php
$sql = mysql_query("SELECT id, name, value FROM table WHERE cond = 'value'");
$s = mysql_fetch_assoc($sql);
// Dump variable containing the result of the MySQL query
var_dump($s);
?>
The second parameter lets you specify the height of the box. Default is 9em, but if you're expecting a huge output you'll probably want a higher value.
<?php
var_dump($s, "17em");
?>
Happy var_dumping.
flyfy1 at gmail dot com (2011-06-22 00:22:39)
for output the var as string, include this function:
<?php
function var_dump_to_string($var){
$output = "<pre>";
_var_dump_to_string($var,$output);
$output .= "</pre>";
return $output;
}
function _var_dump_to_string($var,&$output,$prefix=""){
foreach($var as $key=>$value){
if(is_array($value)){
$output.= $prefix.$key.": \n";
_var_dump_to_string($value,$output," ".$prefix);
} else{
$output.= $prefix.$key.": ".$value."\n";
}
}
}
?>
(say if you want to output $var to string $output)
<?
php $output = var_dump_to_string($var);
?>
divinity76 at gmail dot com (2011-04-23 06:53:00)
a html-encoded var_dump
<?php
function htmlvardump(){ob_start(); $var = func_get_args(); call_user_func_array('var_dump', $var); echo htmentities(ob_get_clean());}
?>
(creds: ekneuss / mOo @ irc.freenode.net/#php )
andresa dot ms at gmail dot com (2010-09-03 12:56:24)
I made this recursive version of var_dump to show array values into a HTML table.
<?php
#Recursive Funcition
function dump_table($var, $title=false, $level=0)
{
if($level==0)
{
echo '<table width="400" border="0" cellspacing="1" cellpadding="3" class="dump">';
if($title)
echo '<tr>
<th align="center" colspan="2">'.$title.'</th>
</tr>';
echo '
<tr>
<th align="right">VAR NAME</th>
<th align="left">VALUE</th>
</tr>';
}
else
{
echo '<tr>
<td colspan="2">
<table width="100%" border="0" cellspacing="3" cellpadding="3" class="dump_b">
</td>
</tr>';
}
foreach($var as $i=>$value)
{
if(is_array($value) or is_object($value))
{
dump_table($value, false, ($level +1));
}
else
{
echo '<tr>
<td align="right" width="50%" >'.$i.'</th>
<td align="left" width="50%" >'.$value.'</th>
</tr>';
}
}
echo '</table>';
}
#### HOW TO USE
$libertadores[0]='Palmeiras';
$libertadores[1]='Sao Paulo';
$libertadores[2]='Santos';
dump_table($libertadores, 'Libertadores - Brazilian Champions');
?>
CSS Styles: http://andresa.net/exemplos/dump_table.css
PHP LIVE DEMO: http://andresa.net/exemplos/dump_table.php
geoff at spacevs dot com (2010-04-07 20:10:59)
var_export does not return the same output as var_dump, if you want the var_dump output in a return you can wrap the call in ob_* functions.
<?PHP
ob_start();
var_dump($_SERVER);
$dump = ob_get_clean();
?>
david at exposito dot mobi (2010-02-07 11:36:35)
If you want to save exactly the content of an array into a variable to save ir later for example, use this:
<?php $xml = var_export($xml, true); ?>
You'll have in your same variable the content readable, instead of written down or anything else
ivolucien at gmail dot calm (2009-12-06 14:12:37)
For the special case where you know that you are only dealing with arrays,
<?php string implode(string $glue, array $pieces) ?>
may be all that's necessary, and the $glue parameter can be used to insert placeholders if you need to do more complex formatting. Nested arrays and such are discussed on the implode() page.
www.phella.net (2009-07-30 10:56:11)
Here is another var_dump() substitution for more compact and informative look. Everything prepared for clear output within HTML environment. Try it and you will love it.
<?php
function dump($value,$level=0)
{
if ($level==-1)
{
$trans[' ']='∴';
$trans["\t"]='⇒';
$trans["\n"]='¶;';
$trans["\r"]='⇐';
$trans["\0"]='⊕';
return strtr(htmlspecialchars($value),$trans);
}
if ($level==0) echo '<pre>';
$type= gettype($value);
echo $type;
if ($type=='string')
{
echo '('.strlen($value).')';
$value= dump($value,-1);
}
elseif ($type=='boolean') $value= ($value?'true':'false');
elseif ($type=='object')
{
$props= get_class_vars(get_class($value));
echo '('.count($props).') <u>'.get_class($value).'</u>';
foreach($props as $key=>$val)
{
echo "\n".str_repeat("\t",$level+1).$key.' => ';
dump($value->$key,$level+1);
}
$value= '';
}
elseif ($type=='array')
{
echo '('.count($value).')';
foreach($value as $key=>$val)
{
echo "\n".str_repeat("\t",$level+1).dump($key,-1).' => ';
dump($val,$level+1);
}
$value= '';
}
echo " <b>$value</b>";
if ($level==0) echo '</pre>';
}
?>
egorinsk at gmail com (2009-02-02 04:08:29)
Note that var_dump reset()'s array internal pointer!
csaba at alum dot mit dot edu (2008-06-25 03:09:07)
Note that var_dump does not do HTML escaping. How does this affect you? Well, if you have references to integers, then var_dump will output
&int(integerValue)
Now ∫ translates into an integral sign, and since the browser may be inclined to overlook the missing semicolon, you may be seeing integrals where you were expecting &int
rich dot schu at gmail dot com (2008-04-09 17:56:27)
Keep in mind if you have xdebug installed it will limit the var_dump() output of array elements and object properties to 3 levels deep.
To change the default, edit your xdebug.ini file and add the folllowing line:
xdebug.var_display_max_depth=n
More information here:
http://www.xdebug.org/docs/display
highstrike at gmail dot com (2008-01-08 05:33:08)
made 2 nifty functions based of what some people contributed here. Hope you find them usefull
usage ... call for the dump function. EG: dump($array, "Array dump");
<?php
////////////////////////////////////////////////////////
// Function: dump
// Inspired from: PHP.net Contributions
// Description: Helps with php debugging
function dump(&$var, $info = FALSE)
{
$scope = false;
$prefix = 'unique';
$suffix = 'value';
if($scope) $vals = $scope;
else $vals = $GLOBALS;
$old = $var;
$var = $new = $prefix.rand().$suffix; $vname = FALSE;
foreach($vals as $key => $val) if($val === $new) $vname = $key;
$var = $old;
echo "<pre style='margin: 0px 0px 10px 0px; display: block; background: white; color: black; font-family: Verdana; border: 1px solid #cccccc; padding: 5px; font-size: 10px; line-height: 13px;'>";
if($info != FALSE) echo "<b style='color: red;'>$info:</b><br>";
do_dump($var, '$'.$vname);
echo "</pre>";
}
////////////////////////////////////////////////////////
// Function: do_dump
// Inspired from: PHP.net Contributions
// Description: Better GI than print_r or var_dump
function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL)
{
$do_dump_indent = "<span style='color:#eeeeee;'>|</span> ";
$reference = $reference.$var_name;
$keyvar = 'the_do_dump_recursion_protection_scheme'; $keyname = 'referenced_object_name';
if (is_array($var) && isset($var[$keyvar]))
{
$real_var = &$var[$keyvar];
$real_name = &$var[$keyname];
$type = ucfirst(gettype($real_var));
echo "$indent$var_name <span style='color:#a2a2a2'>$type</span> = <span style='color:#e87800;'>&$real_name</span><br>";
}
else
{
$var = array($keyvar => $var, $keyname => $reference);
$avar = &$var[$keyvar];
$type = ucfirst(gettype($avar));
if($type == "String") $type_color = "<span style='color:green'>";
elseif($type == "Integer") $type_color = "<span style='color:red'>";
elseif($type == "Double"){ $type_color = "<span style='color:#0099c5'>"; $type = "Float"; }
elseif($type == "Boolean") $type_color = "<span style='color:#92008d'>";
elseif($type == "NULL") $type_color = "<span style='color:black'>";
if(is_array($avar))
{
$count = count($avar);
echo "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:#a2a2a2'>$type ($count)</span><br>$indent(<br>";
$keys = array_keys($avar);
foreach($keys as $name)
{
$value = &$avar[$name];
do_dump($value, "['$name']", $indent.$do_dump_indent, $reference);
}
echo "$indent)<br>";
}
elseif(is_object($avar))
{
echo "$indent$var_name <span style='color:#a2a2a2'>$type</span><br>$indent(<br>";
foreach($avar as $name=>$value) do_dump($value, "$name", $indent.$do_dump_indent, $reference);
echo "$indent)<br>";
}
elseif(is_int($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
elseif(is_string($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color\"$avar\"</span><br>";
elseif(is_float($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
elseif(is_bool($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color".($avar == 1 ? "TRUE":"FALSE")."</span><br>";
elseif(is_null($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> {$type_color}NULL</span><br>";
else echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $avar<br>";
$var = $var[$keyvar];
}
}
?>
vladimir at pixeltomorrow dot com (2007-09-10 00:45:48)
You can also use the PEAR package available at http://pear.php.net/package/Var_Dump
which parses the variable content in a very pleasant manner, a lot more easier to "follow" than the built-in var_dump() function.
Of course there are many others, but I prefer this one, because it's simply to use.
Just add at the begining of your file:
<?php
require('Var_Dump.php'); // make sure the pear package path is set in php.ini
Var_Dump::displayInit(array('display_mode' => 'HTML4_Text'), array('mode' => 'normal','offset' => 4));
?>
then, instead of simply using var_dump($foo), use:
<?php
Var_Dump::display($foo);
?>
Read the documentation if you're looking for different output layouts.
Cheers!
Vladimir Ghetau
thriller dot ze at gmail dot com (2007-08-21 01:49:01)
As Bryan said, it is possible to capture var_dump() output to a string. But it's not quite exact if the dumped variable contains HTML code.
You can use this instead:
<?php
echo '<pre>'; // This is for correct handling of newlines
ob_start();
var_dump($var);
$a=ob_get_contents();
ob_end_clean();
echo htmlspecialchars($a,ENT_QUOTES); // Escape every HTML special chars (especially > and < )
echo '</pre>';
?>
vendiddy at gmail dot com (2007-08-20 11:54:33)
I made a function that I use instead of var_dump. It works well for hierarchical data. The trick is to used nested tables.
May not be the best code but it's not that long so you could improve/modify it. Don't think it will work if any self-referencing is involved.
<?php
function variable_to_html($variable) {
if ($variable === true) {
return 'true';
} else if ($variable === false) {
return 'false';
} else if ($variable === null) {
return 'null';
} else if (is_array($variable)) {
$html = "<table border=\"1\">\n";
$html .= "<thead><tr><td><b>KEY</b></td><td><b>VALUE</b></td></tr></thead>\n";
$html .= "<tbody>\n";
foreach ($variable as $key => $value) {
$value = variable_to_html($value);
$html .= "<tr><td>$key</td><td>$value</td></tr>\n";
}
$html .= "</tbody>\n";
$html .= "</table>";
return $html;
} else {
return strval($variable);
}
}
?>
Try it with this completely made-up data:
<?php
$meeting = array(
'title' => 'Sales Meeting',
'start_time' => array(
'hours' => 11,
'minutes' => 15,
'ampm' => 'am'
),
'end_time' => array(
'hours' => 1,
'minutes' => 30,
'ampm' => 'pm'
),
'attendees' => array(
array('first_name' => 'Bob', 'last_name' => 'Smith', 'email' => 'bobsmith@email.com'),
array('first_name' => 'James', 'last_name' => 'Andrews', 'email' => 'jamesandrews@email.com'),
array('first_name' => 'Tom', 'last_name' => 'Schmoe', 'email' => 'bobsmith@email.com')
)
);
echo variable_to_html($meeting);
?>
php at mikeboers dot com (2007-06-28 13:08:49)
Howdy!
I am working on a pretty large project where I needed to dump a human readable form of whatever into the log files... and I thought var_export was too difficult to read. BigueNique at yahoo dot ca has a nice solution, although I needed to NOT modify whatever was being passed to dump.
So borrowing heavily from BigueNique's (just reworked his function) and someone's idea over in the object cloning page, I came up with the following function.
It makes a complete copy of whatever object you initially pass it, including all recursive definitions and outside objects references, then does the same thing as BigueNique's function. I also heavily reworked what it output, to suit my needs.
<?php
function var_log(&$varInput, $var_name='', $reference='', $method = '=', $sub = false) {
static $output ;
static $depth ;
if ( $sub == false ) {
$output = '' ;
$depth = 0 ;
$reference = $var_name ;
$var = serialize( $varInput ) ;
$var = unserialize( $var ) ;
} else {
++$depth ;
$var =& $varInput ;
}
// constants
$nl = "\n" ;
$block = 'a_big_recursion_protection_block';
$c = $depth ;
$indent = '' ;
while( $c -- > 0 ) {
$indent .= '| ' ;
}
// if this has been parsed before
if ( is_array($var) && isset($var[$block])) {
$real =& $var[ $block ] ;
$name =& $var[ 'name' ] ;
$type = gettype( $real ) ;
$output .= $indent.$var_name.' '.$method.'& '.($type=='array'?'Array':get_class($real)).' '.$name.$nl;
// havent parsed this before
} else {
// insert recursion blocker
$var = Array( $block => $var, 'name' => $reference );
$theVar =& $var[ $block ] ;
// print it out
$type = gettype( $theVar ) ;
switch( $type ) {
case 'array' :
$output .= $indent . $var_name . ' '.$method.' Array ('.$nl;
$keys=array_keys($theVar);
foreach($keys as $name) {
$value=&$theVar[$name];
var_log($value, $name, $reference.'["'.$name.'"]', '=', true);
}
$output .= $indent.')'.$nl;
break ;
case 'object' :
$output .= $indent.$var_name.' = '.get_class($theVar).' {'.$nl;
foreach($theVar as $name=>$value) {
var_log($value, $name, $reference.'->'.$name, '->', true);
}
$output .= $indent.'}'.$nl;
break ;
case 'string' :
$output .= $indent . $var_name . ' '.$method.' "'.$theVar.'"'.$nl;
break ;
default :
$output .= $indent . $var_name . ' '.$method.' ('.$type.') '.$theVar.$nl;
break ;
}
// $var=$var[$block];
}
-- $depth ;
if( $sub == false )
return $output ;
}
// var_log( $var, '$name' ) ;
?>
Hope it works well for you!
Bryan (2007-06-04 09:38:26)
Here's how you use output buffering to save var_dump to a string, as described in the Tip box.
<?php
ob_start();
var_dump($my_variable);
$my_string = ob_get_contents();
ob_end_clean();
?>
Zak Scott (2007-05-24 10:45:48)
One of the most used approaches to this I have is:
<?php
echo "<pre>";
print_r($array); // or var_dump()
echo "</pre><br>";
?>
This is great for debugging purposes, no need for a long-winded debug class in most cases. Unless maybe you have a gigantic project that you didn't build yourself.
kaloyan at gmail dot com (2007-04-26 11:32:32)
We can all agree that var_dump(); output is very spartan looking. The debug data needs to be organized better, and presented in a graceful way. In the era of Web 2.0 it is somewhat strange to use plain text to dump information. A DHTML powered informatiion dumping tool will be quite better - like the the open-source alternative of var_dump(); -- Krumo (http://krumo.sourceforge.net).
It renders the output using DHTML and collapsible nodes, it's layout is "skinable" and you can change it to fit your aesthetic taste. Krumo makes the output "human-readable" for real :) Plus it is compliant with both PHP4 and PHP5. Plus it detects "reference recursion". Plus you can use it to dump all various sort of data like debug back-traces, the superglobals ($_SERVER, $_ENV, $_REQUEST, $_COOKIE, $_GET, $_POST, $_SESSION), all the included files, all the declared classes, all the declared constants, all your PHP settings, all your php.ini values (if it is readable), all the loaded extensions, all the HTTP request headers, all the declared interfaces (for PHP5), all the file paths from INCLUDE_PATH, all the values of any particular INI file. Additionally it is designed to be easy to use - for example you can disable all the Krumo dumps instead of cleaning your code out of all print_r()'s and var_dump()'s. Anyway, if you check the site (http://krumo.sourceforge.net), you can found a lot of examples, demonstrations, documentation and all sort of helpful information.
thc at forestfactory dot de (2007-03-06 00:01:24)
Well, like many others I was looking for a way to get nice dumps of variables. I think I'm about to solve this once and for all; or at least for PHP 5.1. Have a look at my project HLI. http://hli.forestfactory.de
It dumps and highlights not only Arrays and Object but also DOMDocument (as XML), DB results (as table), GD-Images (as PNG), DirectoryIterators (as table), Serialized Strings and many more.
It prints backtrace, object reflection (including PHPDoc) and the position of the dump. Dumps are movable, resizeable and foldable.
It is plugin-based, so its easy to write new dump-modes for other objects/resources. It generates XML output that is parsed by XSLT to HTML and will soon be able to be handled over AJAX (I will do this the next time I program some AJAX stuff).
It runs out of the box (tested with PHP 5.1 and PHP 5.2), but this is only a 0.1 release, so please tell me if something in wrong and I'll be happy to fix it.
Oh, and it's LGPL, so just use and enjoy it. I couldn't work without it any more.
Thomas
sneskid at hotmail dot com (2007-01-19 20:48:38)
Since PHP and Javascript are friends:
<?php
function js_dump($js,$n,$z='') {
if($z) {$a = $z . "['" . $n . "']";}
else {$r = 'var '; $a = $n;}
$r .= $a;
if(is_array($js)) {
$r .= ' = new Array();' . "\r\n";
foreach($js as $k => $v) {
if(is_array($v)) {$r .= js_dump($v, $k, $a);}
else {$r .= $a . "['" . $k . "']" . to_js_safe($v);}
}
}
else {$r .= to_js_safe($js);}
return $r;
}
function to_js_safe($js) {return " = '" . addcslashes($js,"\\'") . "';\r\n";}
// example:
$arr = array();
$arr['hello'] = 'ba\'\\"by';
$arr['arr2']['h'] = 'zero';
$arr['arr2']['j'] = 'one';
$arr['arr2']['2']['0'] = 'zero';
$arr['arr2']['2']['1'] = 'one';
$arr[123] = 'but avoid these names in method 1';
// method 1
foreach($arr as $k=>$v) $j .= js_dump($v, $k);
//or method 2 (probably a better idea)
//$j = js_dump($arr,'result');
//then:
//$j = 'AJAX=' . rawurlencode($j);
echo $j;
?>
js_dump( variable/array to dump , starter name )
It's not very optimized and I'm no fan of recursion, but for small arrays this works well. I left 2 "\r\n" in there for readability, you should take them out.
NOTE it doesn't check for numerically named variables.
The result is Javascript eval() friendly.
See this tutorial if you are new to AJAX programming:
http://www.boutell.com/newfaq/creating/ajaxfetch.html
eric at ITCbrandt dot com swap ITC/brandt (2006-12-30 22:57:27)
Very new to this and really appreciate the contributions of everyone. I really rely on this site . BigueNique inspired me with the last post.
I am writing an application that is WAY above my head and am buried in pages of variables and objects. I really wanted an easier way to read them.
I had two problems - 1. The lists were too long; 2. It was hard to tell where one ended and the other began; 3. By the time I saw my rendered forms, I forgot where my variable listing was. (Yeah, I can't count, get over it - now you know why this is so hard for me)
I had a variable dumping routine that worked better than the print_r, but elegant_dump was MUCH nicer.
I added a little bit of CSS and javascript to mine, and I have a really quick and easy way to display a colored title with a toggle control to expand or contract the variable structure and contents.
It might be too rudimentary for most of you guys, and I'm not answering anyone's question specifically, but perhaps this creative implementation will make someone's life a little easier. At a minimum, It might be a good example of mixing in the different languages which was initially a big challenge for me.
simply call: dump_e($var,[$TracerMessage],[$ColorBackground],[$ColorContentBox]);
I have explained my functions as well as posted the required code to make it work here: http://tech.brandtitc.com/dump_e.php
It is a little too long to post in this venue.
Best Regards.
BigueNique at yahoo dot ca (2006-11-02 20:33:27)
Geez! That was a hard one!
Wanted a more 'elegant' way do dump variable contents, but soon discovered the 'PHP reference problem', which makes it hard to deal recursive occurence of the same variable.
The only way I found to detect recursion was to actually modify the variable content (passed by reference) in order to be able to know that it was actually parsed.
References in PHP are quite confusing and often PHP got some strange behaviors....
TIP: don't use FOREACH($array as $key->$value) with arrays containing references... You'll get the values the references had at the time they were put in the array, not their actual values. You have to do $value=&$a['key']; (notice the amp) otherwise you're screwed!
Enjoy!
<?php
// An elegant dump
// By BigueNique@yahoo.ca
$elegant_dump_indent = '|  ';
function elegant_dump(&$var, $var_name='', $indent='', $reference='') {
global $elegant_dump_indent;
$reference=$reference.$var_name;
// first check if the variable has already been parsed
$keyvar = 'the_elegant_dump_recursion_protection_scheme';
$keyname = 'referenced_object_name';
if (is_array($var) && isset($var[$keyvar])) {
// the passed variable is already being parsed!
$real_var=&$var[$keyvar];
$real_name=&$var[$keyname];
$type=gettype($real_var);
echo "$indent<b>$var_name</b> (<i>$type</i>) = <font color=\"red\">&$real_name</font><br>".br;
} else {
// we will insert an elegant parser-stopper
$var=array($keyvar=>$var,
$keyname=>$reference);
$avar=&$var[$keyvar];
// do the display
$type=gettype($avar);
// array?
if (is_array($avar)) {
$count=count($avar);
echo "$indent<b>$var_name</b> (<i>$type($count)</i>) {<br>".br;
$keys=array_keys($avar);
foreach($keys as $name) {
$value=&$avar[$name];
elegant_dump($value, "['$name']", $indent.$elegant_dump_indent, $reference);
}
echo "$indent}<br>".br;
} else
// object?
if (is_object($avar)) {
echo "$indent<b>$var_name</b> (<i>$type</i>) {<br>".br;
foreach($avar as $name=>$value) elegant_dump($value, "->$name", $indent.$elegant_dump_indent, $reference);
echo "$indent}<br>".br;
} else
// string?
if (is_string($avar)) echo "$indent<b>$var_name</b> (<i>$type</i>) = \"$avar\"<br>".br;
// any other?
else echo "$indent<b>$var_name</b> (<i>$type</i>) = $avar<br>".br;
$var=$var[$keyvar];
}
}
$a=array();
$b['refers to a']=&$a;
$c['refers to b']=&$b;
$a['refers to c']=&$c;
elegant_dump($a,'$a');
/* Outputs:
$a (array(1)) {
| ['refers to c'] (array(1)) {
| | ['refers to b'] (array(1)) {
| | | ['refers to a'] (array) = &$a <-- stops recursing there
| | }
| }
}
Works with objects too: */
$d->ref2f='';
$e->ref2d=&$d;
$f->ref2e=&$e;
$d->ref2f=&$f;
elegant_dump($d,'$d');
/* Outputs:
$d (object) {
| ->ref2f (object) {
| | ->ref2e (object) {
| | | ->ref2d (object) = &$d
| | }
| }
}
*/
?>
jonbarnett at gmail dot com (2006-10-02 12:25:29)
dumping objects that reference each other could lead to infinite recursion
<?php
$brother = new Sibling();
$sister = new Sibling();
$brother->sister = $sister;
$sister->brother = $brother;
var_dump($brother);
/* dumps all of $brother's properties, including "sister", which dumps all of $sister's properties, including "brother", etc. */
?>
Storm (2006-08-19 10:12:37)
ul_var_dump - dump $var to <ul><li></li></ul>
<?php
function ul_var_dump(&$var,$type=0)
{
if(!$type)
echo "<ul type='circle' style='border:1px solid #a0a0a0;padding-bottom:4px;padding-right:4px'>\n<li>";
if(is_array($var))
{
echo "[array][".count($var)."]";
echo "<ul type='circle' style='border:1px solid #a0a0a0;padding-bottom:4px;padding-right:4px'>\n";
foreach($var as $k=>$v)
{
echo "<li>\"{$k}\"=>";
ul_var_dump(&$v,1);
}
echo "</ul>\n";
}
else
echo "[".gettype($var)."][{$var}]</li>\n";
if(!$type)
echo "</ul>\n";
}
?>
andre at webkr dot de (2005-10-04 14:45:56)
var_dump prefixes the variable type with & if the variable has more than one reference.
This is only true for variables that are part of an array, not for scalar types.
Example:
<?php
$a['foo'] = 'other';
$a['bar'] = 'i_have_ref';
$b =& $a['bar'];
var_dump($a);
var_dump($b);
?>
Result:
array(2) {
["foo"]=>
string(5) "other"
["bar"]=>
&string(10) "i_have_ref"
}
string(10) "i_have_ref"
ospinto at hotmail dot com (2005-08-06 21:43:01)
Just created this neat class that dumps a variable in a colored tabular structure similar to the cfdump tag in Coldfusion. Very easy to use and makes it so much easier to see the contents of variable. For examples and download, visit http://dbug.ospinto.com
edwardzyang at thewritingpot dot com (2005-03-20 14:06:13)
If you're like me and uses var_dump whenever you're debugging, you might find these two "wrapper" functions helpful.
This one automatically adds the PRE tags around the var_dump output so you get nice formatted arrays.
<?php
function var_dump_pre($mixed = null) {
echo '<pre>';
var_dump($mixed);
echo '</pre>';
return null;
}
?>
This one returns the value of var_dump instead of outputting it.
<?php
function var_dump_ret($mixed = null) {
ob_start();
var_dump($mixed);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
?>
Fairly simple functions, but they're infinitely helpful (I use var_dump_pre() almost exclusively now).
anon (2005-01-28 06:31:38)
var_dump(get_defined_vars());
will dump all defined variables to the browser.