How to convert PHP array into a string with implode function

Use the implode function whenever you need to convert an array into a string. It has been the standard since PHP 4.

<?php 
  $myPies = ["banana", "apple", "cherry", "pecan"];
  echo "pies I love include: " . implode($myPies, ", ");
  // returns 'Pies I love include: banana, apple, cherry, pecan'

Converting PHP arrays into strings with implode

One of the most common needs that I’ve had to code during my career as a PHP developer is converting arrays into strings. If you haven’t yet, you’ll come across this requirement many times.

There are many different scenarios where this request will arise. You may get JSON data that needs to get converted into a CSV report or you may need to render a list of HTML strings into a final file. Implode will get the job done for you.

Scenario: Convert the list of pies I sell from a PHP multidimensional array into a CSV using implode function

One of the more common scenarios that you will encounter when programming PHP is converting data that may come from an API or database into a CSV file. You may get the data in SQL or a JSON API but the first step will be to generally transform that content into a PHP multidimensional array.

In the following example, I am going to convert this list of pie data that has been transformed into a multidimensional PHP array into a CSV string that I can save to disk or send as API response.

Step 1: Start with the data

Let’s begin by

<?php

  $myColumns = ["name", "price", "quantity"];

  $myPieData = [
    ["banana cream", 5.95, 30],
    ["dutch apple", 4.95, 50],
    ["tiramisu", 6.50, 20]
   ];

Step 2: Document finished sample of converted array to csv string and required PHP logic

Before I begin writing my logic, I like to document my finished result and the steps that I take to make it happen. Writing my logic out in English keeps me from rewriting my code multiple times because I know the steps that it will take to convert the PHP array into a string. It’s a good practice as it also helps keep future developers (including yourself) understanding what you are trying to accomplish.



<?php

  // We need to convert the following php array into a csv string
  // the first list is the column headers.
  // The second list is my data.
  // The columns in the pie data align exactly with the column headers
  // ex: 
  //.  name, price, quantity
  //   my pie, 2.99, 32
  // 
  // I need to do 3 things to make this work. 
  // #1 - I need setup my string variable that I'm going to return.
  // #2 - I need to convert and add my column heading array to my response string
  // #3 - I need to loop through my multidimensional pie data and add line breaks with each item.

  $myColumns = ["name", "price", "quantity"];

  $myPieData = [
    ["banana cream", 5.95, 30],
    ["dutch apple", 4.95, 50],
    ["tiramisu", 6.50, 20]
   ];

Step 3: Program your PHP data array to string conversions

The final step to convert these PHP arrays into a csv string is to actually write the code and return the response. Let’s get started.

<?php

  // We need to convert the following php array into a csv string
  // the first list is the column headers.
  // The second list is my data.
  // The columns in the pie data align exactly with the column headers
  // ex: 
  //.  name, price, quantity
  //   my pie, 2.99, 32
  // 
  // I need to do 3 things to make this work. 
  // #1 - I need setup my string variable that I'm going to return.
  // #2 - I need to convert and add my column heading array to my response string
  // #3 - I need to loop through my multidimensional pie data and add line breaks with each item.

  $myColumns = ["name", "price", "quantity"];

  $myPieData = [
    ["banana cream", 5.95, 30],
    ["dutch apple", 4.95, 50],
    ["tiramisu", 6.50, 20]
   ];

  // The csv string to return.
  $csvContent = '';

  // Create the first header row 
  $csvContent .= implode($myColumns, ",") . "\n";

  // Now here's the fun part.
  // We'll want to map the array data and add to the end of our csv string
  // First step is to loop the the parent array.
  foreach($myPieData as $k => $pie) {
    // Now lets add the pie data to our csv content.
    $csvContent .= implode($pie, ",") . "\n";
  }

  // That wasn't too bad.
  // Let's return our csv data now

  return $csvData;

Ok, that is a great job. We were able to create a csv of our wonderful pie data. Now I can send this spreadsheet to my retailers so they know the cost and quantity of pies that I have to sell.

but… data never comes in this clean, does it?

Extended Scenario: Convert multidimensional associative array into a string

The above scenario was good because we were able to see some good logic, but let’s be real. Our PHP array data will never be that easy. We are likely to get the data unorganized, poorly structured, and out of order.

Let’s add more complexity to our PHP array to string conversion scenario and make it more realistic. We will transform the pieData PHP array into a multidimensional associative array. Each of the child pie arrays will have keys related to their name, price, and quantity.

New scenario data

<?php

  // We need to convert the following php array into a csv string
  // the first list is the column headers.
  // The second list is my data.
  // The columns in the pie data align exactly with the column headers
  // ex: 
  //.  name, price, quantity
  //   my pie, 2.99, 32
  // 
  // I need to do 3 things to make this work. 
  // #1 - I need setup my string variable that I'm going to return.
  // #2 - I need to convert and add my column heading array to my response string
  // #3 - I need to loop through my multidimensional pie data and add line breaks with each item.

  $myColumns = ["name", "price", "quantity"];

  $myPieData = [
    ["name" => "banana cream", "price" => 5.95, "quantity" => 30],
    ["name" => "dutch apple", "quantity" => 50,  "price" => 4.95],
    ["quantity" => 20, "name" => "tiramisu",  "price" => 6.50]
   ];

See the updates? That pie data is a little more complex. It has key/value pairs and isn’t in the right order. We will need to sort our arrays before we add them to our csvContent.

Let’s make it happen

<?php

  // We need to convert the following php array into a csv string
  // the first list is the column headers.
  // The second list is my data.
  // The columns in the pie data align exactly with the column headers
  // ex: 
  //.  name, price, quantity
  //   my pie, 2.99, 32
  // 
  // I need to do 3 things to make this work. 
  // #1 - I need setup my string variable that I'm going to return.
  // #2 - I need to convert and add my column heading array to my response string
  // #3 - I need to loop through my multidimensional pie data and add line breaks with each item.

  $myColumns = ["name", "price", "quantity"];

  $myPieData = [
    ["name" => "banana cream", "price" => 5.95, "quantity" => 30],
    ["name" => "dutch apple", "quantity" => 50,  "price" => 4.95],
    ["quantity" => 20, "name" => "tiramisu",  "price" => 6.50]
   ];

  // Create the first header row 
  $csvContent .= implode($myColumns, ",") . "\n";

  // Now here's the fun part.
  // We'll want to map the array data and add to the end of our csv string
  // First step is to loop the the parent array.
  foreach($myPieData as $k => $pie) {

    //**
    // NEW FUNCTIONALITY - SORT OUR ARRAYS
    //
    ksort($pie);

    // Now lets add the pie data to our csv content.
    $csvContent .= implode($pie, ",") . "\n";
  }

  // That wasn't too bad.
  // Let's return our csv data now

  return $csvData;

Oh. that wasn’t too bad! It was just 1 function added to the logic to convert this PHP multi-dimensional associative array into a string. It’s funny how sometimes things that appear complex in our head can be simplified.

I do admit that I took the easy route in the above example. I set it up so that my CSV columns were aligned alphabetically. This would’ve been much more complex if I needed to put quantity before price.

Simple convert PHP arrays to string functions

As you can see, even with the most complex scenarios, it is pretty straightforward to convert PHP arrays into strings using the implode function. I have come across several codebases where developers made it more complex than necessary. They use loops instead of the function because they need to setup their string in a certain format. This is an incorrect way of looking at the problem if you feel like you need to complicate it. Setup your variables then do your implode.

Thank you and let me know what other ‘PHP arrays’ questions that you may have or scenarios and I’ll try my best to help.


Article Categories

Article Tags

    © 2022 Confident.Systems