PHP- print_r() Function


In this article, we will go over the PHP print_r() function.

The print_r() function is a function which can be used to show the contents, or make-up, of an array.

Let's say, for example, we create the following array in PHP.

$students= array("Steve", "Bob", "Tom", "Gary");

If we just used the following line to show display the array, it would not work:

echo $students;

This would produce the following output in PHP:


An array is a special object in PHP. A programmer cannot print out the contents of an array, as shown above, simply with the echo or print function.

However, applying the print_r() function, can be used for showing all of the contents of an array.

So the line of code would be:


The above line of code would yield the following in PHP:

Array ( [0] => Steve [1] => Bob [2] => Tom [3] => Gary )

The following print_r() function shows all of the contents of the array. Since we created an array of 4 elements, the array has elements with keys of 0-3. 0 is the first element and 3 is the last element. Since our first element is "Steve", it is assigned to the 0 key. Since our second element is "Bob", it assigned to key 1. Since our third element is "Tom", it is assigned to key 2. Since our fourth element is "Gary", it is assigned to key 3.

Thus, the print_r() function will show all the keys and values of an array.

Another Example

The print_r() function can be used with any type of array.

Another example we will show its use with is an array where the elements are assigned a value.

Let's create the array:

$children= array("Peter"=>age 7, "John"=>age 4, "Lisa"=>age 9);

If we print out the following line with the print_r() function, with the line:


This line would produce the following PHP code:

Array ( [Peter] => 7 [John] => 4 [Lisa] => 9 )

You can see that now because of the print_r function, we can see that the keys for the $children array are "Peter", "John", and "Lisa" and the values are 7, 4, and 9.

This can be a good array if we wanted to have an array with a list of children and their ages.

We can also assign strings to strings for arrays.

Check out the following array:

$people= array("James"=>gmail, "Scott"=>yahoo, "Fred"=>gmail);

When printing this out, with the line:


We get the following PHP output:

Array ( [James] => gmail [Scott] => yahoo [Fred] => gmail )

This is a good array when you have a list of people with the type of email accounts they have.

This is how the print_r function works. It is a good function for finding out all of the contents of an array, the keys and values, for troubleshooting purposes. It normally is not used just to display the array, since it is formatted so strictly. There are better ways to display an array that comes out in a much prettier manner.

HTML Comment Box is loading comments...