Echo PHP Array: 10 Code Examples to Print Keys & Values (2023)

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

How to echo an array in PHP

There are multiple ways to echo arrays in PHP. Use a foreach loop, implode, print_r, or var_dump functions to display an array’s keys & values. I recommend using either var_dump or print_r if you are debugging whereas loops are useful when you need to access the data.

This article explains how to echo an array in PHP and includes a section about how we can print out a PHP array. Stick to the article and you will have better insights by the end of this article.

Let’s start without any further ado.

Echo PHP Arrays with Value PHP Code Examples

<?php 

$fruit = ["apple" => 2, "banana" => 3, "orange" => 7];

// Print an array using var_dump:
var_dump($fruit);


// Print an array using print_r:
print_r($fruit);


// Echo array keys using a foreach loop.
echo "fruits: ";
$i = 1;

foreach ($fruit as $item => $total) {
 echo $item;
 if ($i !== count($fruit) {
    echo ", ";
 }
 $i++;
}

// Display array keys using array_keys & implode function
echo "Fruits Available: " . implode(",", array_keys($fruit));


// Display array values using implode function
echo "Fruit totals: " . implode(",", $fruit);


// echo array keys & values in an html list using a foreach loop
// You can put PHP variables inside of double quotes. Checkout this example.
echo "<ul>Fruits:";
foreach ($fruits as $item => $total) {
   echo "<li>$item : $total</li>";
}
echo "</ul>";


// Display the contents of an array in an html table.
// This is similar to the previous but displays in table.
echo "<table>";
echo "<th>";
echo "<td>Fruit</td>";
echo "<td>Total</td>";
echo "</th>";

foreach ($fruits as $item => $total) {
  echo "<tr>";
  echo "<td>$item</td>";
  echo "<td>$total</td>";
  echo "</tr>";
}


// ADVANCED: Use recursion to echo multidimensional array values
$fruitDetails = [
  "apples" => [
    "green" => 2,
    "mcintosh" => 5,
    "fuji" => 3,
    "honeycrisp" => 6
  ]
];

echo "My Fruits:";
function recursiveValuePrinter(array $list) {
    echo "<ul>";

    foreach ($list as $type => $details) {
      if (is_array($details)) {
         recursiveValuePrinter($details);
       } else {
         echo "<li>$type : $details</li>";
       }
    }

   echo "</ul>";
}

recursiveValuePrinter($fruitDetails);

Table of Contents

Why You Can’t Echo a PHP Array

PHP can’t echo arrays by design. The echo function is used to display & print string values that are used by various runtimes. Webservers are a good example. They need to display HTML content to browsers. Browsers don’t understand PHP or any such programming language. They interpret the HTML.

Therefore, it would create significant problems if PHP allowed you to echo a PHP array.

<?php
 
$arr = ["Hello", "World"];
 
echo $arr; //PHP Warning:  Array to string conversion
 
?>

So what do you do?

Luckily, there are many options available for you to use. I have used them all. Choosing the right one depends on what you are trying to do.

Don’t worry. We’ll walk you through the details.

Echo all PHP array values using the implode function

The implode function is the most common way to print & display PHP array values. The implode function separates each element in an array with a common separator.

I use this function to create CSV content from simple arrays.

implode(string $separator, array $array): string

The function joins the elements using the separator argument. The following example uses this function to join the array elements into a string and then echo it.

PHP Implode Array Code Example

<?php
 
$arr = ["Hello", "World"];
 
echo implode(" ", $arr); //Hello World
 
?>

Voila! The “echo” prints the string that it receives from the implode function. Here we have an overhead of a function call. But there are better ways. Let’s explore further.

Echo all PHP array keys using the implode function

The implode function can also print the keys of an array. You will need to use the array_keys function to transfer the keys into a new array that stores them as values. It is an easy two-step process.

There are other methods to echo PHP array keys, but I like this method because it’s simple and easy to read.

PHP Print All Array Keys PHP Code Example

<?php

$fruits = ["apples" => 1, "bananas" => 3, "oranges" => 0];

// step 1: create a new variable with the keys from the fruits
$fruitTypes = array_keys($fruits);

// step 2: print the values from the arrays
echo "fruits:" . implode(", ", $fruitTypes);

You can print the entire PHP array using the print_r function. The print_r function is really useful whenever you are debugging data. I use it a lot whenever I need to review the content response from an API. It displays both the key and values in a human-readable way.

PHP print_r  prints human-readable information about an array. It doesn’t include any intricate data type information. I always prefer it while working with arrays.

Print PHP Arrays Using print_r Code Example

<?php
 
$arr = ["Hello", "World"];
 
print_r($arr);
 
/*
OUTPUT
Array
(
    [0] => Hello
    [1] => World
)
*/
 
?>

Voila! No overhead of calling an extra function. PHP print_r is a one-liner to output an array.

Print an array in PHP with var_dump

The var_dump function can also be used to echo & debug PHP arrays like print_r. The difference is that var_dump also includes the value type (string, integer, boolean, array, etc). I use the var_dump quite often in debugging financial data where the values may be numbers in either string, integer or float types.

PHP var_dump prints an array with details about the data types of all the elements. The output appears a little bit messy especially if you’re dealing with multidimensional arrays.

Echo PHP array using var_dump function code example

<?php
 
$arr = ["Hello", "World", 1, true];
 
var_dump($arr);
 
/*
OUTPUT
array(4) {
  [0]=>
  string(5) "Hello"
  [1]=>
  string(5) "World"
  [2]=>
  int(1)
  [3]=>
  bool(true)
}
*/
 
?>

See! It prints out the array with information about the data types of every element.

Echo an array in PHP with var_export

The var_export function is another useful method to print & debug a PHP array. It is very similar to the print_r function. The difference between print_r & var_export is that you don’t have to print the results with var_export. You may want to just return the data.

Honestly, I have never used this function in any meaningful way. I will stick with print_r most of the time.

PHP var_export is a useful function to echo an array in PHP. It either prints out or returns a parsable string representation of an array. 

var_export(mixed $value, bool $return = false): ?string

If the return argument is true it would return the value rather than printing it. Here’s how.

<?php
 
$arr = ["Hello", "World", 1, true];
 
var_export($arr);
 
/*
array (
  0 => 'Hello',
  1 => 'World',
  2 => 1,
  3 => true,
)
*/
 
?>

Alternatively, set the return to true and store the return value to an array. You can then print the variable using any of the above methods.

<?php
 
$arr = ["Hello", "World", 1, true];
 
$arr_output = var_export($arr, true);
 
print_r($arr_output);
 
/*
array (
  0 => 'Hello',
  1 => 'World',
  2 => 1,
  3 => true,
)
*/
 
?>

Voila! We have seen pretty much all the options to print an array in PHP. 

Echo all PHP Array Keys & Values into HTML

Use a foreach loop whenever you want to Echo PHP array values into HTML. The foreach loop will execute any code that exist inside of it for each element of an array that is passed into it.

I often use this loop when creating tables or HTML lists.

Display PHP Arrays into HTML List Code Example

<?php 

$fruits = ["apples" => 1, "bananas" => 2, "oranges" => 5];

echo "<ul>";
foreach ($fruits as $type => $total) {
   echo "<li>$type : $total</li>";
}
echo "</ul>";

Echo Keys & Values from PHP Arrays

This article includes all the methods to echo an array in PHP. First, it overviews the PHP “echo” construct with the implode function. Next, it goes through the print_r function. Following print_r, the article shows how to echo an array in PHP using var_dump. Finally, it includes a section about var_export.

Hopefully, this article answers your question. Stay tuned at FuelingPHP if you’re interested in similar articles and tutorials about PHP.

Learn More About Loops in PHP

Want to learn how to use loops in PHP? This article is part of our series on looping through PHP arrays. Check out our full series to become a PHP array loop ninja.

PHP Fundamentals Recommendations

This article is part of our content on PHP Fundamentals. It includes the core concepts that build upon the foundation of writing high-quality PHP code. If you are looking to grow your PHP development abilities. Check out the following recommended affiliate resources.

We do make a commission if you do choose to buy through our links. It is one of the ways that help support our mission here at FuelingPHP.

Book: Fundamentals of Web Development

This book is for you if you are starting to learn how to build websites. It is more than just an “intro to programming” book. You will learn the concepts and tips on what goes into creating a high-quality website. Today’s websites are more than text on a screen. They are highly complex applications that encourage user experience. Learn the fundamentals of good web development with this book.

Check it out on Amazon

Book: Programming in PHP (O’Reilly)

O’Reilly should not need any introduction. They are the top publishers when it comes to books on programming and technology. This book fits well within their vast library. If you are newer to the PHP language or want to keep a solid reference by your side. I highly recommend this book for your collection.

Check it out on Amazon

Book: Design Patterns in PHP

I highly recommend this book to any intermediate-level web developer. It takes the theories and best practices of writing high-quality code via design patterns and applies them to PHP. It is a great resource to take your career to the next level

Check it out on Amazon

Video Course: PHP Fundamentals (Pluralsight)

Want to quickly learn PHP? This PHP Fundamentals course is ideal for beginner PHP developers. It is a deep dive into the concepts, structures and well “fundamentals” of PHP development. It includes high-quality video & interactive resources that teach you really fast. I highly recommend this if you are getting started in your PHP journey.

Click here for a 10-day free trial to Pluralsight

Complete Learning Path: Web Development (Pluralsight)

You should definitely check out this learning path from Pluralsight. They have a huge list of video courses, training, and interactive lessons on growing your web development career. You get access to the full library of hundreds of resources for a single monthly subscription. It truly is like Netflix for your career.

Click here to see details (10-day free trial included)

Want more reviews? Check out our HUGE list of Beginner Web Development Books We’ve Researched and Reviewed for you.

Learn More About Loops in PHP

Want to learn how to use loops in PHP? This article is part of our series on looping through PHP arrays. Check out our full series to become a PHP array loop ninja.

PHP Fundamentals Recommendations

This article is part of our content on PHP Fundamentals. It includes the core concepts that build upon the foundation of writing high-quality PHP code. If you are looking to grow your PHP development abilities. Check out the following recommended affiliate resources.

We do make a commission if you do choose to buy through our links. It is one of the ways that help support our mission here at FuelingPHP.

Book: Fundamentals of Web Development

This book is for you if you are starting to learn how to build websites. It is more than just an “intro to programming” book. You will learn the concepts and tips on what goes into creating a high-quality website. Today’s websites are more than text on a screen. They are highly complex applications that encourage user experience. Learn the fundamentals of good web development with this book.

Check it out on Amazon

Book: Programming in PHP (O’Reilly)

O’Reilly should not need any introduction. They are the top publishers when it comes to books on programming and technology. This book fits well within their vast library. If you are newer to the PHP language or want to keep a solid reference by your side. I highly recommend this book for your collection.

Check it out on Amazon

Book: Design Patterns in PHP

I highly recommend this book to any intermediate-level web developer. It takes the theories and best practices of writing high-quality code via design patterns and applies them to PHP. It is a great resource to take your career to the next level

Check it out on Amazon

Video Course: PHP Fundamentals (Pluralsight)

Want to quickly learn PHP? This PHP Fundamentals course is ideal for beginner PHP developers. It is a deep dive into the concepts, structures and well “fundamentals” of PHP development. It includes high-quality video & interactive resources that teach you really fast. I highly recommend this if you are getting started in your PHP journey.

Click here for a 10-day free trial to Pluralsight

Complete Learning Path: Web Development (Pluralsight)

You should definitely check out this learning path from Pluralsight. They have a huge list of video courses, training, and interactive lessons on growing your web development career. You get access to the full library of hundreds of resources for a single monthly subscription. It truly is like Netflix for your career.

Click here to see details (10-day free trial included)

Want more reviews? Check out our HUGE list of Beginner Web Development Books We’ve Researched and Reviewed for you.

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Click here to get started

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.