Using implode() to Convert an Array to a String

If you’ve read the last two articles, you know how the explode() functMODX logoion 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:

[code language=”php”]
$nameArray = array(
0 => ‘BobRay’,
1 => ‘JohnDoe’,
2 => ‘JaneRoe’,
);
[/code]

 

Using implode()

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

[code language=”html”]
Users: BobRay, JohnDoe, JaneRoe
[/code]

 

The Code

Here’s the code to do it:

[code language=”php”]
$nameArray = array(
0 => ‘BobRay’,
1 => ‘JohnDoe’,
2 => ‘JaneRoe’,
);
$output = ‘Users: ‘ . implode(‘, ‘, $nameArray);
return $output;
[/code]

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:

[code language=”php”]
$output = ‘Users: <br />’ . implode(‘<br />&nbsp;&nbsp;’, $nameArray);
[/code]

 

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.

 


For more information on how to use MODX to create a web site, see my web site Bob’s Guides, or
better yet, buy my book: MODX: The Official Guide.

Looking for quality MODX Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , | Posted under MODX, MODX | RSS 2.0

Author Spotlight

Bob Ray

Bob Ray is the author of MODX: The Official Guide and over 30 MODX add-on components. He hosts Bob's Guides, a source of valuable information for MODX users, and has been very active in the MODX Forums with over 19,000 posts.

Leave a Reply

Your email address will not be published. Required fields are marked *