How to Print an Array in PHP

Tyler Tyler (304)
1 minute

Printing an array in PHP is one of the most basic and necessary functions. Here are a few tricks and tools to make it easier. These steps should work for the latest edition of PHP but you can visit this guide to learn how to check your PHP version.

PHP×1

Howchoo is reader-supported. When you buy through links on our site, we may earn a small affiliate commission at no cost to you.

The print_r command prints human readable information about a variable and it is quite useful for arrays. You can use it like this:

$names = array('Lloyd', 'Harry');
print_r($names);

and the browser will give you:

Array([0] => Lloyd [1] => Harry)

Nest the print_r function inside of the <pre> tags in order to get more readable output, like this:

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

and that will give you this:

Array
(
    [0] => Lloyd
    [1] => Harry
)

If you're working on a large project, you might consider writing a custom function and auto-loading or including it onto every page:

function print_rx($arr) {
    echo "<pre>"; print_r($arr); echo "</pre>";
}
Tyler Tyler (304)
0

In this guide I'm going to describe how to get started with PHP and MySQL.