Many developers have submitted bugs to the PHP development team with regards to print_r showing protected and private properties of objects (PHP 5). This is not a bug; sensitive information (ex. database connection object) should be encapsulated within a private member function of your class.
print_r
(PHP 4, PHP 5)
print_r — 변수에 관한 정보를 사람이 읽기 좋게 출력합니다.
설명
Note: return 인자는 PHP 4.3.0에서 추가되었습니다.
print_r()은 변수에 대한 정보를 사람이 읽을 수 있는 방법으로 표시합니다. string, integer, float이 주어지면, 값을 그대로 출력합니다. array가 주어지면, 키와 요소를 알아볼 수 있는 형태로 표현합니다. object에 대해서도 비슷하게 표현합니다. var_dump()와는 달리, print_r()과 var_export()는 PHP 5에서 protected 및 private 속성도 보여줍니다.
print_r()은 배열 포인터를 마지막으로 이동합니다. 처음으로 되돌리려면 reset()을 사용하십시오.
<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>
출력은:
<pre> Array ( [a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z ) ) </pre>
print_r()의 출력을 가져오려면, return 인자를 사용하십시오. 이 인자를 TRUE로 설정하면, print_r()은 출력을 표시(기본값)하는 대신, 반환값으로 내보냅니다.
Example#1 return 인자 예제
<?php
$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); //$results가 print_r의 출력을 가집니다.
?>
Note: 4.3.0 이전 버전의 PHP에서 print_r()의 출력을 가져오려면, 출력 제어 함수를 이용하십시오.
Note: PHP 4.0.4 이전에는, 주어진 array이나 object가 자기 자신에의 직접적/비직접적 참조를 포함하고 있으면 print_r()은 무한 루프에 빠졌습니다. 예를 들면, print_r($GLOBALS)가 해당합니다. $GLOBALS는 자기 자신에의 참조를 포함하고 있는 전역 변수이기 때문입니다.
참고: ob_start(), var_dump(), var_export().
print_r
28-Aug-2008 01:58
17-Aug-2008 01:44
I was having problems using print_r because I didn't like the fact that if tags where included in the array it would still be parsed by the browsers.
Heres a simple fix for anyone who is having the same problem as I did. This will output your text properly for viewing through the browser instead of the browser's "view source" or CLI.
Script:
<?php
$MyArray[0]="<div align='center'>My Text</div>";
echo "<pre>".htmlspecialchars(print_r($MyArray,true))."</pre>";
?>
Output:
<pre>Array
(
[0] => <div align='center'>My Text</div>
)
</pre>
01-Aug-2008 06:51
I use a function. Since browsers neglect extra spaces and line feeds.
<?php
function print_a($subject){
echo str_replace("=>","⇒",str_replace("Array","<font color=\"red\"><b>Array</b></font>",nl2br(str_replace(" "," ",print_r($subject,true)))));
}
?>
28-Jun-2008 01:21
I have written a nice debugging function.
This function handles arrays beautifully.
<?php
//Debug variables, $i and $k are for recursive use
function DebugDisplayVar($input, $name = "Debug", $i = "0", $k = array("Error")){
if(is_array($input))
{ foreach ($input as $i => $value){
$temp = $k;
$temp[] = $i;
DebugDisplayVar($value, $name, $i, $temp);}
}else{//if not array
echo "$".$name;//[$k]
foreach ($k as $i => $value){
if($value !=="Error"){echo "[$value]";}
}
echo " = $input<br>";
} }
//outputs
Debug[0] = value
Debug[1] = another value
ect...
?>
13-May-2008 02:49
You cannot use print_r(), var_dump() nor var_export() to get static member variables of a class. However, in PHP5 you can use Reflection classes for this:
<?php
$reflection = new ReflectionClass('Static');
print_r($reflection->getStaticProperties());
?>
09-Apr-2008 05:27
@highstrike at gmail dot com 08-Jan-2008 02:34
You have an bug in your debug script, the script only prints public properties of the exported object.
If you want to export all object properties (public, private, protected) to an array, then simply cast the object to an array:
<?php
class some
{
public $pub = 1;
protected $prot = 2;
private $priv = 3;
}
var_dump( (array) new some() );
?>
result:
--------------
array(3) {
["pub"]=>
int(1)
["*prot"]=>
int(2)
["somepriv"]=>
int(3)
}
28-Mar-2008 03:07
There is a library to create nice output of variables, arrays, hash-tables and even objects. It is great for developing/debugging and looks very much better than any print_r output.
Usage:
<?php
debug::show($myVar, 'caption');
?>
You can download it for free at http://sourceforge.net/projects/phpcorestdfuncs
For an example take a look at http://demo.corvent.ch/stdfuncs/
06-Mar-2008 08:13
Another slight modification to the previous post to allow for empty array elements
added the following lines after the first preg_match block
<?php
} else if ($expecting == 2 && preg_match('/^\[(.+?)\] \=\>$/', $trim, $matches)) { // array element
// the array element is blank
list ($fullMatch, $key) = $matches;
$topArray[$key] = $element;
}
?>
29-Feb-2008 10:30
A slight modification to the previous post to allow for arrays containing mutli line strings. haven't fully tested it with everything, but seems to work great for the stuff i've done so far.
<?php
function print_r_reverse(&$output)
{
$expecting = 0; // 0=nothing in particular, 1=array open paren '(', 2=array element or close paren ')'
$lines = explode("\n", $output);
$result = null;
$topArray = null;
$arrayStack = array();
$matches = null;
while (!empty($lines) && $result === null)
{
$line = array_shift($lines);
$trim = trim($line);
if ($trim == 'Array')
{
if ($expecting == 0)
{
$topArray = array();
$expecting = 1;
}
else
{
trigger_error("Unknown array.");
}
}
else if ($expecting == 1 && $trim == '(')
{
$expecting = 2;
}
else if ($expecting == 2 && preg_match('/^\[(.+?)\] \=\> (.+)$/', $trim, $matches)) // array element
{
list ($fullMatch, $key, $element) = $matches;
if (trim($element) == 'Array')
{
$topArray[$key] = array();
$newTopArray =& $topArray[$key];
$arrayStack[] =& $topArray;
$topArray =& $newTopArray;
$expecting = 1;
}
else
{
$topArray[$key] = $element;
}
}
else if ($expecting == 2 && $trim == ')') // end current array
{
if (empty($arrayStack))
{
$result = $topArray;
}
else // pop into parent array
{
// safe array pop
$keys = array_keys($arrayStack);
$lastKey = array_pop($keys);
$temp =& $arrayStack[$lastKey];
unset($arrayStack[$lastKey]);
$topArray =& $temp;
}
}
// Added this to allow for multi line strings.
else if (!empty($trim) && $expecting == 2)
{
// Expecting close parent or element, but got just a string
$topArray[$key] .= "\n".$line;
}
else if (!empty($trim))
{
$result = $line;
}
}
$output = implode(n, $lines);
return $result;
}
/**
* @param string $output : The output of a multiple print_r calls, separated by newlines
* @return mixed[] : parseable elements of $output
*/
function print_r_reverse_multiple($output)
{
$result = array();
while (($reverse = print_r_reverse($output)) !== NULL)
{
$result[] = $reverse;
}
return $result;
}
$output = '
Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
[3] => Array
(
[nest] => yes
[nest2] => Array
(
[nest] => some more
asffjaskkd
)
[nest3] => o rly?
)
)
)
some extra stuff
';
var_dump(print_r_reverse($output), $output);
?>
This should output
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
array(4) {
[0]=>
string(1) "x"
[1]=>
string(1) "y"
[2]=>
string(1) "z"
[3]=>
array(3) {
["nest"]=>
string(3) "yes"
["nest2"]=>
array(1) {
["nest"]=>
string(40) "some more
asffjaskkd"
}
["nest3"]=>
string(6) "o rly?"
}
}
}
string(18) "nsome extra stuffn"
Added:
else if (!empty($trim) && $expecting == 2)
{
// Expecting close parent or element, but got just a string
$topArray[$key] .= "\n".$line;
}
19-Feb-2008 12:34
This is a better print_r reverse algorithm, that works with arbitrary nested arrays. Anything else it treats as strings. The second function allows you to take a string with multiple print_r results concatenated, and returns the result of parsing each of them.
<?php
/**
* @param string &$output : The output of a print_r call; this parameter is DESTRUCTIVE, and will be set to the remainder
* of $output which is not parsed.
* @return mixed : the first parseable element of $output
*/
function print_r_reverse(&$output)
{
$expecting = 0; // 0=nothing in particular, 1=array open paren '(', 2=array element or close paren ')'
$lines = explode("\n", $output);
$result = null;
$topArray = null;
$arrayStack = array();
$matches = null;
while (!empty($lines) && $result === null)
{
$line = array_shift($lines);
$trim = trim($line);
if ($trim == 'Array')
{
if ($expecting == 0)
{
$topArray = array();
$expecting = 1;
}
else
{
trigger_error("Unknown array.");
}
}
else if ($expecting == 1 && $trim == '(')
{
$expecting = 2;
}
else if ($expecting == 2 && preg_match('/^\[(.+?)\] \=\> (.+)$/', $trim, $matches)) // array element
{
list ($fullMatch, $key, $element) = $matches;
if (trim($element) == 'Array')
{
$topArray[$key] = array();
$newTopArray =& $topArray[$key];
$arrayStack[] =& $topArray;
$topArray =& $newTopArray;
$expecting = 1;
}
else
{
$topArray[$key] = $element;
}
}
else if ($expecting == 2 && $trim == ')') // end current array
{
if (empty($arrayStack))
{
$result = $topArray;
}
else // pop into parent array
{
// safe array pop
$keys = array_keys($arrayStack);
$lastKey = array_pop($keys);
$temp =& $arrayStack[$lastKey];
unset($arrayStack[$lastKey]);
$topArray =& $temp;
}
}
else if (!empty($trim))
{
$result = $line;
}
}
$output = implode(n, $lines);
return $result;
}
/**
* @param string $output : The output of a multiple print_r calls, separated by newlines
* @return mixed[] : parseable elements of $output
*/
function print_r_reverse_multiple($output)
{
$result = array();
while (($reverse = print_r_reverse($output)) !== NULL)
{
$result[] = $reverse;
}
return $result;
}
$output = '
Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
[3] => Array
(
[nest] => yes
[nest2] => Array
(
[nest] => some more
)
[nest3] => o rly?
)
)
)
some extra stuff
';
var_dump(print_r_reverse($output), $output);
?>
The above example will output:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
array(4) {
[0]=>
string(1) "x"
[1]=>
string(1) "y"
[2]=>
string(1) "z"
[3]=>
array(3) {
["nest"]=>
string(3) "yes"
["nest2"]=>
array(1) {
["nest"]=>
string(9) "some more"
}
["nest3"]=>
string(6) "o rly?"
}
}
}
string(20) "
some extra stuff
"
06-Feb-2008 03:31
A one line command that serves to nl2br but have it so it displays in html is
function nl2br2($arg){print(nl2br(str_replace(' ',' ',print_r($arg,true))));}
31-Jan-2008 04:52
A simple function that will output an array more easily to read than print_r();
<?php
function echo_array($array,$return_me=false){
if(is_array($array) == false){
$return = "The provided variable is not an array.";
}else{
foreach($array as $name=>$value){
if(is_array($value)){
$return .= "";
$return .= "['<b>$name</b>'] {<div style='margin-left:10px;'>\n";
$return .= echo_array($value,true);
$return .= "</div>}";
$return .= "\n\n";
}else{
if(is_string($value)){
$value = "\"$value\"";
}
$return .= "['<b>$name</b>'] = $value\n\n";
}
}
}
if($return_me == true){
return $return;
}else{
echo "<pre>".$return."</pre>";
}
}
?>
08-Jan-2008 05:34
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];
}
}
?>
30-Oct-2007 05:27
Here's a PHP version of print_r which can be tailored to your needs. Shows protected and private properties of objects and detects recursion (for objects only!). Usage:
void u_print_r ( mixed $expression [, array $ignore] )
Use the $ignore parameter to provide an array of property names that shouldn't be followed recursively.
<?php
function u_print_r($subject, $ignore = array(), $depth = 1, $refChain = array())
{
if ($depth > 20) return;
if (is_object($subject)) {
foreach ($refChain as $refVal)
if ($refVal === $subject) {
echo "*RECURSION*\n";
return;
}
array_push($refChain, $subject);
echo get_class($subject) . " Object ( \n";
$subject = (array) $subject;
foreach ($subject as $key => $val)
if (is_array($ignore) && !in_array($key, $ignore, 1)) {
echo str_repeat(" ", $depth * 4) . '[';
if ($key{0} == "\0") {
$keyParts = explode("\0", $key);
echo $keyParts[2] . (($keyParts[1] == '*') ? ':protected' : ':private');
} else
echo $key;
echo '] => ';
u_print_r($val, $ignore, $depth + 1, $refChain);
}
echo str_repeat(" ", ($depth - 1) * 4) . ")\n";
array_pop($refChain);
} elseif (is_array($subject)) {
echo "Array ( \n";
foreach ($subject as $key => $val)
if (is_array($ignore) && !in_array($key, $ignore, 1)) {
echo str_repeat(" ", $depth * 4) . '[' . $key . '] => ';
u_print_r($val, $ignore, $depth + 1, $refChain);
}
echo str_repeat(" ", ($depth - 1) * 4) . ")\n";
} else
echo $subject . "\n";
}
?>
Example:
<?php
class test {
public $var1 = 'a';
protected $var2 = 'b';
private $var3 = 'c';
protected $array = array('x', 'y', 'z');
}
$test = new test();
$test->recursiveRef = $test;
$test->anotherRecursiveRef->recursiveRef = $test;
$test->dont->follow = 'me';
u_print_r($test, array('dont'));
?>
Will produce:
test Object (
[var1] => a
[var2:protected] => b
[var3:private] => c
[array:protected] => Array (
[0] => x
[1] => y
[2] => z
)
[recursiveRef] => *RECURSION*
[anotherRecursiveRef] => stdClass Object (
[recursiveRef] => *RECURSION*
)
)
21-Sep-2007 05:17
If you need to import an print_R output back to an array you could use this.
This could also be (ab)used to convert a object into a array...
<?php
function object2array($printr) {
$newarray = array();
$a[0] = &$newarray;
if (preg_match_all('/^\s+\[(\w+).*\] => (.*)\n/m', $printr, $match)) {
foreach ($match[0] as $key => $value) {
(int)$tabs = substr_count(substr($value, 0, strpos($value, "[")), " ");
if ($match[2][$key] == 'Array' || substr($match[2][$key], -6) == 'Object') {
$a[$tabs+1] = &$a[$tabs][$match[1][$key]];
}
else {
$a[$tabs][$match[1][$key]] = $match[2][$key];
}
}
}
return $newarray;
}
?>
19-Jun-2007 04:01
This works around the hacky nature of print_r in return mode (using output buffering for the return mode to work is hacky...):
<?php
/**
* An alternative to print_r that unlike the original does not use output buffering with
* the return parameter set to true. Thus, Fatal errors that would be the result of print_r
* in return-mode within ob handlers can be avoided.
*
* Comes with an extra parameter to be able to generate html code. If you need a
* human readable DHTML-based print_r alternative, see http://krumo.sourceforge.net/
*
* Support for printing of objects as well as the $return parameter functionality
* added by Fredrik Wollsén (fredrik dot motin at gmail), to make it work as a drop-in
* replacement for print_r (Except for that this function does not output
* paranthesises around element groups... ;) )
*
* Based on return_array() By Matthew Ruivo (mruivo at gmail)
* (http://se2.php.net/manual/en/function.print-r.php#73436)
*/
function obsafe_print_r($var, $return = false, $html = false, $level = 0) {
$spaces = "";
$space = $html ? " " : " ";
$newline = $html ? "<br />" : "\n";
for ($i = 1; $i <= 6; $i++) {
$spaces .= $space;
}
$tabs = $spaces;
for ($i = 1; $i <= $level; $i++) {
$tabs .= $spaces;
}
if (is_array($var)) {
$title = "Array";
} elseif (is_object($var)) {
$title = get_class($var)." Object";
}
$output = $title . $newline . $newline;
foreach($var as $key => $value) {
if (is_array($value) || is_object($value)) {
$level++;
$value = obsafe_print_r($value, true, $html, $level);
$level--;
}
$output .= $tabs . "[" . $key . "] => " . $value . $newline;
}
if ($return) return $output;
else echo $output;
}
?>
Built on a function earlier posted in these comments as stated in the Doc comment. Cheers! /Fredrik (Motin)
26-Apr-2007 11:30
We can all agree that print_r() 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 print_r(); -- 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.
22-Mar-2007 01:03
We had an interesting problem dumping an object that
contained embedded HTML. The application makes use
of buffer manipulation functions, so print_r's 2nd argument
wasn't helpful. Here is how we solved the problem:
$object = new ObjectContainingHTML();
$savedbuffercontents = ob_get_clean();
print_r($object);
$print_r_output = ob_get_clean();
ob_start();
echo $savedbuffercontents;
echo htmlentities($print_r_output);
01-Mar-2007 11:34
None of the function to output to HTML was working for me so I had to write something that suited my needs. It's probably super not efficient but, hey it works well for me on a small scale.
function print_r_html($data,$return_data=false)
{
$data = print_r($data,true);
$data = str_replace( " "," ", $data);
$data = str_replace( "\r\n","<br>\r\n", $data);
$data = str_replace( "\r","<br>\r", $data);
$data = str_replace( "\n","<br>\n", $data);
if (!$return_data)
echo $data;
else
return $data;
}
Simple, isn't? :)
22-Feb-2007 10:47
For those of you needing to print an array within a buffer callback function, I've created this quick function. It simply returns the array as a readable string rather than printing it. You can even choose whether to return it in normal text-mode or HTML. It's recursive, so multi-dimensial arrays are supported. I hope someone finds this useful!
<?php
function return_array($array, $html = false, $level = 0) {
$space = $html ? " " : " ";
$newline = $html ? "<br />" : "\n";
for ($i = 1; $i <= 6; $i++) {
$spaces .= $space;
}
$tabs = $spaces;
for ($i = 1; $i <= $level; $i++) {
$tabs .= $spaces;
}
$output = "Array" . $newline . $newline;
foreach($array as $key => $value) {
if (is_array($value)) {
$level++;
$value = return_array($value, $html, $level);
$level--;
}
$output .= $tabs . "[" . $key . "] => " . $value . $newline;
}
return $output;
}
?>
07-Feb-2007 12:45
I've got four functions for printing arrays out in a readable fashion, I hope someone finds them useful.
//prints an array in a HTML table. Top row is the keys.
function table( $array ) {
$array = array_values( $array );
$keys = array_keys( $array[0] );
echo '<table border="1"><tr>';
foreach( $keys as $key ) {
echo '<td>'.$key.'</td>';
}
echo '</tr>';
foreach( $array as $row ) {
echo '<tr>';
foreach( $row as $value ) {
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
echo '</table>';
}
//print_r enclosed in a <pre>, except it will always print something, even if the variable is null, number 0 or false. It also lets you label the dump.
function dump( $var, $label=null ) {
if( $var === '' or $var === null or $var === 0 ) {
var_dump( $var );
return;
}
echo '<pre style="text-align: left; font-size: 10px;">';
if( $label ) {
echo $label."\n";
}
print_r( $var );
echo '</pre>';
}
//This one gives you output you can copy and paste back into your PHP code to recreate the array.
function dump_array( $array, $tabs=1 ) {
$html = "<pre style=\"text-align: left; font-size: 10px;\">array( \n";
foreach( $array as $key => $val ) {
$html .= str_repeat( "\t", $tabs )."'$key' => ";
if( is_array( $val ) ) {
$html .= dump_array( $array, $tabs+1 );
} else {
$html .= "'$val',\n";
}
}
$html .= ')</pre>';
return $html;
}
//just add header( 'content-type: application/vnd.ms-excel' ) and you've got an excel file.
function excel( $array ) {
$array = array_values( $array );
$keys = array_keys( $array[0] );
foreach( $keys as $key ) {
echo $key."\t";
}
echo "\n";
foreach( $array as $row ) {
foreach( $row as $value ) {
echo $value."\t";
}
echo "\n";
}
}
17-Jan-2007 06:11
i've been using a similar idea like Sawey's for quite a long time,
but was always disappointed that you don't see the name of the
variable passed to the function (eg calling it many times, you don't
know which value was provided by a certain variable at a certain time).
so i combined sawey's idea with one found on php.net to solve that problem.
for shellscripting the function only uses <pre>-tags when called in the web.
<?php
/* how print_r should be ;) */
function my_r(&$var, $scope=false, $label=false){
if (is_string($scope) && $label==false) $label=$scope;
if (!is_array($scope)) $scope = &$GLOBALS;
$origin = $var;
$var = $checker = "very_weird_value#".rand()."#isnt_it";
$vname = false;
foreach ($scope as $key => $value){
if ($value === $checker){ $vname = "\$".$key; }
if (is_array($value) && $key!="GLOBALS"){
if ($pfad=aver($var,$value)){
$vname = "\$${key}[\"". implode("\"][\"",$pfad)."\"]";
}
}
if (is_object($value)){
if ($pfad=aver($var,get_object_vars($value))){
if (sizeof($pfad)<2) $vname = "\$${key}->".$pfad[0];
else{
$vname ="\$${key}->".$pfad[0];
$vname.="[\"".implode("\"][\"", array_slice($pfad,1))."\"]";
}
}
}
if ($vname) break;
}
$var = $origin;
if ($_SERVER["SERVER_NAME"] && !isset($_SERVER["TERM"])) echo "<pre>";
if ($vname){
echo $vname;
if ($label) echo " #" . $label . "# ";
else echo ": ";
}else{
if ($label) echo "$label: ";
}
print_r($var);
if ($_SERVER["SERVER_NAME"] && !isset($_SERVER["TERM"])) echo "</pre>";
}
/* this function is needed to check in multidimensional arrays
if the value of interest exists. if yes, the path is returned */
function aver($needle,$haystack) { // array value exists recursive
foreach($haystack as $key=>$val) {
if(is_array($val) && $needle != $val && $key != "GLOBALS") {
if($foo=aver($needle,$val)) return array_merge(array($key),$foo);
}elseif($val === $needle) return array($key);
}
return false;
}
?>
