PHP: Using print_r for debugging

September 27, 2006

When programming PHP you sometimes need to look at http post or get data (That is, a the data submitted in a form) The simplest way to do this is to to use php’s builtin function print_r, which will parse any array and print the indeces and array values. For post and get data, you should look at the corresponding array, $_POST and $_GET, respectively.

There are two things worth noting about print_r. First thing is that print_r is a regular function, and not a language construct like echo and print. Without going into detail, this means you need to put parentheses around the argument when calling it, unlike for print/echo. Second thing worth noting is that print_r outputs raw text. This includes line breaks, which will normally be parsed as spaces by by your browser, which will make the data almost unreadable. The easy solution to this is to put a pre block around the data. So we arrive at this code:

<?PHP
echo '<pre>';
print_r($_GET);
echo '</pre>';
?>

Here’s a sample output:

Array
(
    [userid] => 23
    [password] => qweasd
)

However, as mentioned, print_r can print any array. Except for your own arrays, these might come in handy when debugging: $_GET/$_POST (As mentioned above) $_SERVER (A lot of information) $_SESSION (Session data, if your application uses sessions) getallheaders() (Shows all http headers. Call it like this: print_r(getallheaders()); ). There are probably even more useful arrays than these, but they were the ones that I came to think of now. Happy debugging!

Btw, the blog idfw06 linked to me, so I’d better link back. (:

One Response to “PHP: Using print_r for debugging”

  1. ale Says:

    And don’t forget half-brother var_dump.


Leave a comment