Printing Arrays Using print_r()

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.

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

Will produce the following result.

Array
(
[0] => 1
[1] => 34
[2] => 6
[3] => 2325
[4] => 5
[5] => 34
[6] => 2
)

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.
CAPTCHA
6 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.