How to Echo or Print an Array in PHP

In this tutorial, we will learn some different ways of printing/echoing an array in PHP.

 

The easiest way to show data from an array in PHP is to loop through it using a foreach statement and echo each item individually.

 

$items = ['apple','orange','apricot'];

foreach ($items as $key => $value) {
  echo "Key is: ". $key ." value is: ". $value ."\n";
}
Key is: 0 value is: apple
Key is: 1 value is: orange
Key is: 2 value is: apricot

 

Display Array in PHP with print_r()

The native PHP print_r() function will show the entire array including index numbers and values without needing to loop through it. Here is a demonstration of how to use print_r():

 

$items = ['apple','orange','apricot'];

print_r($items);
Array
(
 [0] => apple
 [1] => orange
 [2] => apricot
)

 

var_dump() is a powerful native PHP function that will output detailed information about any type of data contained in a PHP program, including arrays.

 

 

$items = ['apple','orange','apricot'];

var_dump($items);
array(3) {
[0]=>
string(5) "apple"
[1]=>
string(6) "orange"
[2]=>
string(7) "apricot"
}

 

var_dump() is especially useful if you need to see extra details such as its length and the data type of each element on top of index and value information.

array print

Related Tutorials