Print_r() PHP Function

Define and print a PHP array

Young man working on laptop computer at home
Fotostorm/E+/Getty Images

An array in PHP computer programming contains a group of similar objects that are the same type and size. The array can contain integers, characters, or anything else with a defined data type.

The print_r PHP function is used to return an array in a human readable form. It is written as:

print_r($your_array)

In this example, an array is defined and printed. The tag <pre> indicates the following code is preformatted text. This tag causes the text to be displayed in a fixed-width font. It preserves line breaks and spaces, making it easier for the human observer to read.

<pre>
<?php
$Names = array ('a' => 'Angela', 'b' => 'Bradley', 'c' => array ('Cade', 'Caleb'));
print_r ($Names);
?>
</pre>

When the code is run, the results looks like this:

Array
(
[a] => Angela
[b] => Bradley
[c] => Array
(
[0] => Cade
[1] => Caleb
)
)

Variations of Print_r

You can store the result of print_r in a variable with a second parameter to print_r. This technique prevents any output from the function.

Augment the function of print_r with var_dump and var_export to show protected and private properties of the objects, including type and value. The difference of the two is that var_export returns valid PHP code, whereas var_dump does not.

Uses for PHP

PHP is a server-side language used to add enhanced features to a website developed in HTML, such as surveys, shopping carts, login boxes, and CAPTCHA codes. You can use it to build an online community, integrate Facebook with your website, and generate PDF files. With PHP's file-handling functions, you can create photo galleries and you can use the GD library included with PHP to generate thumbnail images, add watermarks, and resize and crop images.

If you host banner ads on your website, PHP rotates them at random. The same feature can be used to rotate quotations. It is easy to set up page redirects using PHP and if you are wondering how often your visitors check out your website, use PHP to set up a counter.