Printing Arrays Using print_r()

20th December 2007

When debugging PHP code the print_r can be useful if you want to know what an array or object contains. It will take any variable as input and will print off as much information as it can about that variable. The following code.

  1. $array = array(1,34,6,2325,5,34,2);
  2. echo "<pre>";
  3. print_r($array);
  4. echo "</pre>";

Will produce the following result.

  1. (
  2. [0] => 1
  3. [1] => 34
  4. [2] => 6
  5. [3] => 2325
  6. [4] => 5
  7. [5] => 34
  8. [6] => 2
  9. )

Notice the use of the pre tags. This is to allow the output to be properly formatted on screen, otherwise it looks messy. Of course you could just view source, but I find the formatted output easier on the eye. You could also write it out like this:

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

The print_r() function also takes a second parameter. This is a boolean value that tells it to return the result, rather than to output it straight to the browser. So the following code will work just the same.

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

print_r() is a great way of looking at the values contained in an array without having to write a for loop every time you want to debug it. Additionally, it will also take objects as input and will print them off in much the same manner.

You could also use var_dump() in the same kind of way, but I find it gives a little too much information so it is only useful if you want to know the data type of the variables you are looking at.

Add new comment

The content of this field is kept private and will not be shown publicly.