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!

Community
  • 1
  • 1
Elias Ranz
  • 401
  • 1
  • 6
  • 21
  • 1
    If you "view source" on the html page you will see the newlines show up. – Danny Apr 11 '13 at 18:06
  • 1
    I'll just advise against using (and promoting) the buggy and outdated Krumo. It hasn't seen updates in 5+ years, does not show private members, in some cases even alters displayed data (!) and is buggy all around. **Disclaimer**: I am the author of Kint, I released it as a superior replacement for Krumo. – raveren Apr 12 '13 at 12:07
  • @Raveren how would I implement Kint into a MVC such as CodeIgniter? Is there a way that I can load it in as just a class so that it can be a library? – Elias Ranz Apr 12 '13 at 20:36
  • It depends, I don't use CodeIgniter, but the universal way is to add `require 'kint/dir/Kint.php'` somewhere in the bootstrap process. – raveren Apr 15 '13 at 11:56

11 Answers11

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>';
}
G-Nugget
  • 8,666
  • 1
  • 24
  • 31
  • 2
    you need the TRUE in the second paramater of print_r because it outputs it as a string, if you don't then the `
    ` won't take effect if you don't include it.
    – Elias Ranz Apr 11 '13 at 18:08
  • 4
    @elias `print_r($var, true)` returns a string. `print_r($var, false)` and `print_r($var)` echo the result. – G-Nugget Apr 11 '13 at 18:10
  • 1
    @Elias you are correct that if you pass `TRUE` as the second param, `print_r()` returns the output rather than printing it. But this code is working because `echo` lines **are** separate. `echo '
    ' . print_r($var, TRUE) . '
    ';` <=== in this case, you do need the second param.
    – AKS Apr 11 '13 at 18:13
  • @AyeshK so if I seperate it onto multiple lines then it will split it up? – Elias Ranz Apr 11 '13 at 18:14
  • 1
    Yes, the first `echo
    ` call prints the pre tag first, so the next `print_r()`'s output is shown well in the browser, and the other echo closes the pre tag.
    – AKS Apr 11 '13 at 18:18
  • Right that makes sense, I didn't think about it that way, thanks! – Elias Ranz Apr 11 '13 at 18:25
  • Function names like `r()` and `d()` is poor advice in modern development -- it is devoid of any intuitive-ness. Modern professional code would implement a more declarative naming convention. – mickmackusa May 09 '21 at 23:34
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

leeoniya
  • 1,071
  • 1
  • 9
  • 25
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!)

rubo77
  • 19,527
  • 31
  • 134
  • 226
AKS
  • 4,618
  • 2
  • 29
  • 48
  • Thanks @ITroubs. Going to give it a try right now (honestly I thought Krumo has no competitors :) ) – AKS Apr 11 '13 at 18:16
  • I think one of my friends uses something similar if not this in CakePHP, looked nice, but didn't know if it was just something built into Cake. – Elias Ranz Apr 11 '13 at 18:20
  • i use kint with a little modification that moves al kint output to the top of the page (because sometimes there was not enough place to view the output) – ITroubs Apr 11 '13 at 18:20
  • Krumo and kint look good. One thing I'm not sure on, though, is if they will show private class properties. I know the built-in functions can show them, but other methods might not be able to show them. – G-Nugget Apr 11 '13 at 18:20
  • 1
    @ITroubs I may have to look into using kint, then. I looked at it briefly and it says that it needs zero configuration, which it would definitely have over krumo. – G-Nugget Apr 11 '13 at 18:23
  • @ITroubs even if it's private to a specific object? – Elias Ranz Apr 11 '13 at 18:23
  • @Elias i think it should yes. – ITroubs Apr 11 '13 at 18:27
  • Are either of these pretty to implement into a MVC such as CodeIgniter, that's what I'm currently using, or does it have a built in debugger that I don't know of? – Elias Ranz Apr 11 '13 at 18:45
  • Hey there, author of Kint here. It's heaps and bounds better than krumo. If you dump an object you get all of its members - private or otherwise, static class variables, all class methods and their documentation and in some cases even more info - eg. if it implements an iterable interface, you see the iterated content - all in a readable tabbed interface. @ITroubs: how did you make the output display above everythig else? I'm guessing this change is framework specific? Otherwise, I'd implement it as an option. – raveren Apr 12 '13 at 12:03
  • @Raveren yes it is somehow speciffic. I just inserted a special empty tag at the top of my body and using jquery i moved all output inside of that div. – ITroubs Apr 12 '13 at 12:29
  • That's what I thought, I have a todo to make it optionally output at the very **end** of the page tough, that one's easy. – raveren Apr 12 '13 at 12:48
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/

Hackerman
  • 12,139
  • 2
  • 34
  • 45
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,
     ...
     )
Elias Ranz
  • 401
  • 1
  • 6
  • 21
0

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

alxgb
  • 543
  • 8
  • 18
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.

bwoebi
  • 23,637
  • 5
  • 58
  • 79
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)

PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58
0

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

Fabio
  • 23,183
  • 12
  • 55
  • 64
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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
shotex
  • 349
  • 5
  • 10
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!).

pyb
  • 4,813
  • 2
  • 27
  • 45
mickmackusa
  • 43,625
  • 12
  • 83
  • 136