How To Convert Array To String With PHP

The Answer: Using implode()

As I’ve always said, PHP has the answer for everything, and the conversion of an array to a flat string is no exception.

Using implode to convert an array to a string

The really great thing about this conversion is it’s a one-liner function call.

The implode function takes two parameters,

  • Glue (string), a specified string that will essentially be concatenated to each of the array values (Sticking the values together). Although note that the Glue (what I like to call a delimiter) doesn’t have to be used, an array on its own can be passed in but the string representation will print without anything in between the values,
  • Pieces (array), the array we want to convert to a string.

In the following 2 examples, notice the Glue is a string of white space which will print a space between each of the array values when we echo it.

Example 1

$facebookPost = [
     "user" => "CodeWall",
     "post" => "Check out our latest post on CodeWall",
     "timestamp" => date('Y-m-d H:i:s'),
     "share_count" => 6,
     "like_count" => 9
];

echo implode(" ", $facebookPost);

Output

CodeWall Check out our latest post on CodeWall 2020-05-29 10:40:23 6 9

Example 2

$mySampleArray = ["one", "two", "three"];
echo implode(" ", $mySampleArray);

Output

one two three

Example 3

In this particular example, notice the glue parameter has been removed, leaving the function to convert the array to a string without any delimiter.

$mySampleArray = ["one", "two", "three"];
echo implode($mySampleArray); // without glue parameter

onetwothree

 

Posted in PHP

Leave a Reply