How to “echo” an array in PHP

The PHP echo() function is great for spitting out your basic types of values, such as strings and numbers. But if you want to see the values, or even better the data structure, of an array you will need to use a different method. This is where print_r() comes in handy.

The print_r() function prints human-readable or human-friendly information about a variable, not just arrays. For this subject I’ll illustrate some examples using print_r with arrays.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
 
// array
$fruits = array('apple', 'orange', 'banana');
 
// associated array
$fruitColors = array('apple' => 'red', 'orange' => 'orange', 'banana' => 'yellow');
 
// multi-dimensional array
$cars = array(
    'Chevrolet' => array('Corvette', 'Camaro', 'Impala'),
    'Lotus' => array('Elise', 'Esprit', 'Europa'),
    'Lamborghini' => array('Renenton', 'Diablo', 'Countach')
);
 
// print the arrays
print_r($fruits);
print_r($fruitColors);
print_r($cars);
 
?>

The output for the previous code should look like the text below.

Array
(
    [0] => apple
    [1] => orange
    [2] => banana
)
Array
(
    [apple] => red
    [orange] => orange
    [banana] => yellow
)
Array
(
    [Chevrolet] => Array
        (
            [0] => Corvette
            [1] => Camaro
            [2] => Impala
        )
 
    [Lotus] => Array
        (
            [0] => Elise
            [1] => Esprit
            [2] => Europa
        )
 
    [Lamborghini] => Array
        (
            [0] => Renenton
            [1] => Diablo
            [2] => Countach
        )
 
)

This should give you a good idea of how you can use the print_r() function in your PHP code. Enjoy!