11

What is the best way to debug an array so that you can see what values are being stored and in what keys in the array they are being stored at? Also how do you make it so that it's easier to look at visually so that you don't have to keep looking through the array for the key and it's value in the one line print_r() function?

EDIT:

I now realize that print_r() is not the only solution to debugging arrays. So if you have alternate solutions that would be lovely as well to learn more about debugging.

EDIT2:

Ayesh K, ITroubs and Robert Rozas have mentioned both Krumo and Kint this far, if you have others feel free to post them. Also thanks to Raveren for writing Kint!

4

11 回答 11

10

Every PHP developer should have a function for this. My function is below:

function r($var){
    echo '<pre>';
    print_r($var);
    echo '</pre>';
}

To nicely print data, just call r($data);. If you want more detail, you could use this function:

function d($var){
    echo '<pre>';
    var_dump($var);
    echo '</pre>';
}
于 2013-04-11T18:06:03.320 回答
5

here's mine...

demo: http://o-0.me/dump_r/
repo: https://github.com/leeoniya/dump_r.php
composer: https://packagist.org/packages/leeoniya/dump-r

you can restyle it via css if needed.

enter image description here

于 2013-04-21T07:08:39.620 回答
4

Everyone suggests print_r which is in core and works really well. But when it comes to view a large array, print_r() drives me nuts narrowing down the output.

Give a try to krumo. It nicely prints the array with visual formatting, click-expand and it also gives you the exact array key call that you can simply copy and paste.

<?php
 krumo($my_array);
?>

Itroubs mentioned Kint as a better alternative to Krumo. (Thanks ITroubs!)

于 2013-04-11T18:09:19.593 回答
3

I use var_dump....now if you want some more, check out this site:

http://raveren.github.io/kint/

and

http://krumo.sourceforge.net/

于 2013-04-11T18:06:37.050 回答
2

The best practice to visually see the values/keys in an array is the following:

echo "<pre>".print_r($array,TRUE)."</pre>";

The true is required as it changes it into a string, the output will be:

array(
     key1 => value,
     key2 => value,
     ...
     )
于 2013-04-11T18:06:26.073 回答
0

Quick solution: Open the source code of the page, and you'll see print_r's output in several lines and perfectly indented.

于 2013-04-11T18:03:50.773 回答
0

print_r is not one lined (it uses \n as new line, not <br>). Add a <pre>...</pre> around it to show the multiple lines.

于 2013-04-11T18:04:14.670 回答
0

print_r() uses \n as its line delimiter. Use <pre> tags or view the page's source code to make it look right. (on Windows, Linux works with \n)

于 2013-04-11T18:05:13.700 回答
0

You can either look source code or use var_dump() or print_r() with <pre>...</pre>

于 2013-04-11T18:05:24.880 回答
0

I personally, never liked all this fancy stuff, i use print_r() because it's not overwhelming and it gives enough information.

Here is mine:

if(isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Debug')
{
    echo '<strong><i>FILE : </i></strong>'.__FILE__.'<strong> <i>LINE : </i></strong>'.__LINE__.'<pre>';
    print_r($var);
    echo '</pre>';
    die;
}

This if statement is to ensure that other people don't see what you've printed. There is a good add-on for Mozila-Firefox and Google Chrome called "user agent switcher", where you can create your custom user agents. So I create a user agent called "Debug", and when I'm working, I change the user agent.

If I use default user agent nothing will happen and the page wont die;, only you and people who also change the user agent to "Debug" will see the printed variable. This is helpful if you want to debug a problem in a production environment, and you don't want the page to die; and it is also good if other people are also working on the project and you don't want to interrupt them by killing the page.

Then I echo out the current File and Line, this is helpful when you work in a framework or CMS or any other big project with thousands of files and folders, and while debugging, if you might forget where you've typed die; or exit; and you need to remember where you've been and which variables you have printed.

I use the NetBeans IDE for PHP development, I have a macro set up so when you select a variable and use it, it will paste this debugging tool to the text editor and put the selection inside a print_r(); function. If you also use NetBeans, you can use this macro:

cut-to-clipboard
"if(isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Debug')"
insert-break
"{"
insert-break
"echo '<strong><i>FILE : </i></strong>'.__FILE__.'<strong> <i>LINE :</i></strong>'.__LINE__.'<pre>';"
insert-break
"print_r("
paste-from-clipboard
remove-line-begin 
");"
insert-break
"echo '</pre>';"
insert-break
"die;"

You just need to select the $variable and use the macro.

于 2016-05-21T21:52:31.603 回答
0

To be honest, I'm surprised that print_r() (print human-readable). There are three native functions which each have their advantages and disadvantages in printing data to a document. As mentioned elsewhere on the page, wrapping your output in <pre> ... </pre> tags will be very beneficial in respecting newlines and tabbing when printing to an html document.

The truth is that ALL php developers, from newbie to hobbyist to professional to grand wizard level 999, need to have the following techniques in their toolbox.

Here is a non-exhaustive demo which exposes some of the differences.

  1. var_export() is the format that I use most often. This function wraps strings in single quotes. This is important in identifying trailing whitespace characters and differentiating numeric types versus string types. To maintain the integrity of the output data and permit instant portability of the data into a runnable context, single quotes and backslashes are escaped -- don't let this trip you up.

  2. print_r() is probably my least-used and the least-informative function when data needs to be inspect. It does not wrap strings in any kind of delimiting character so you will not be able to eyeball invisible characters. It will not escape backslashes, single quotes, or double quotes. It wraps keys in square braces which may cause confusion if your keys contain square braces originally.

  3. var_dump() is uniquely powerful in that it expresses data types AND the byte count for strings. This is hands-down the best tool when there is a risk that you might have unexpected multibyte characters interfering with the success/stability of your script.

Depending on your php version and which function you use, you may see differing values with same input data. Pay careful attention to float values.

debug_zval_dump() very much resembles the output of var_dump(), but also includes a refcount. This native function is not likely to provide any additional benefit relating to "debugging an array".

There are also non-native tools which may be of interest (most of which I've never bothered to use). If you are using a framework, Laravel for instance, offers dd() (dump and die) as a diagnostic helper method. Some devs love the collapsed/expandable styling of this tool, but other devs loudly voice their annoyance at the tedious clicking that is necessary to expose nested levels of data.

As a sideways approach to printing iterable data, you could entertain the idea of echoing a json-encoded string with the JSON_PRETTY_PRINT. This may reveal some things that could cause trouble like multibyte and whitespace characters, but don't forget that this is literally "encoding" the data. In other words, it is converting data from one form to another and it will mutate certain occurrences in the process. Like var_export(), a json encoded string is an excellent form to maintain data integrity when it needs to be tranferred from one place to another (like from your project to your Stack Overflow question!).

于 2021-05-10T11:58:01.217 回答