Print an Array in PHP using print_r and var_dump, With Examples

PHP Print Array

This article will show you several methods on how to print an array in PHP, with some examples.

Arrays in PHP can be processed using foreach loops to interact with each element in the array. This article focuses on directly printing an array in full rather than each element individually.

Using echo to Print an Array (It Won’t Work)

You might think that you can just use the echo statement to print an array in PHP – this is not the case, as seen below:

<?php

    // Define an array containing fruit
    $array = array("apple", "banana", "cherry", "lemon");

    echo $array;

?>

The only output you’ll receive from the echo statement when printing an array is:

Array

…which isn’t all that useful. Here’s how to print out meaningful details on an array variable.

Using the print_r Function to Print an Array

The PHP print_r() function prints human-readable information from a variable. For arrays, it prints the full array, including keys and values.

<?php

    // Define an array containing fruit
    $array = array("apple", "banana", "cherry", "lemon");

    print_r($array);

?>

This will output:

Array ( [0] => apple [1] => banana [2] => cherry [3] => lemon ) 

…which contains the key (index/position) and value for each value in the array – much more useful!

Using the var_dump Function to Print an Array

The var_dump() function can also be used in a similar manner to print_r().

The PHP var_dump() function returns a given variable or value’s properties, including the value and type. It works through the variable’s properties or value recursively doing the same.

<?php

    // Define an array containing fruit
    $array = array("apple", "banana", "cherry", "lemon");

    var_dump($array);

?>

This will output:

array(4) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=> string(6) "cherry" [3]=> string(5) "lemon" } 

This contains the key and value for each value in the array and the variable type of each item in the array, and the array itself.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *