Using implode() to Convert an Array to a String

Create a string from an array with implode()


If you've read the last two articles, you know how the explode() function works. The implode() function does just the opposite. It converts an array to a delimiter-separated string. In this article we'll take a look at how it works and what you can do with it.


The Array

Consider our array of usernames from a previous article:

$nameArray = array(
    0 => 'BobRay',
    1 => 'JohnDoe',
    2 => 'JaneRoe',
);

Using implode()

We want to present the list of users in the array like this:

Users: BobRay, JohnDoe, JaneRoe

The Code

Here's the code to do it:

$nameArray = array(
    0 => 'BobRay',
    1 => 'JohnDoe',
    2 => 'JaneRoe',
);
$output = 'Users: ' . implode(', ', $nameArray);
return $output;

The first argument to implode() is the delimiter that will separate the elements of the list in the output. Notice that we've added a space after the comma to make the list look better. The second argument is the name of the array to process.

The delimiter in the first argument can be anything you want as long as it's a string. If you wanted to put the list items on separate lines, for example, and indent them two spaces, you could do this:

$output = 'Users: <br />&nbsp;&nbsp;' . implode('<br />&nbsp;&nbsp;', $nameArray);

Coming Up

This technique will only work with simple, numeric arrays. If you call it on an associative array, the keys (the left-hand members of each element) will be ignored. What if you want to display an associative array as a list and show both the keys and their values? We'll see how to do that in the next article.



Comments (0)


Please login to comment.

  (Login)