Comma, Separated, Values,

I recently realized how much of the art of programming is just lots of little tricks that you pick up along the way. I’m resolving to share these little tricks, in the hopes that others will do the same, either on their blogs or in the comments here.

Here’s one involving an array and building a string of comma separated values.

Let us pretend you have an array called Tags. It contains the tag names as strings.

Tags[0] = "awesome"
Tags[1] = "groovy"
Tags[2] = "existential"

You want to display these as CSV

awesome, groovy, existential

How do you do it? You might think “well, I want to print a tag, then a comma, then the next tag, and so on until I’m done”

for(i = 0; i < Tags.length; i++) {
    print Tags[i] + ', '

You probably see what’s wrong already. The above code prints

awesome, groovy, existential,

OK. Maybe you could get clever:

first = true;for(i = 0; i < Tags.length; i++) {
    if(!first) { print ', ' }
    print Tags[i]


for(i = 0; i < Tags.length; i++) {
    if(i == Tags.length - 1) { print ', ' }
    print Tags[i]

But ouch. Don’t do that.

Many languages provide a built in function for converting arrays into CSV strings. PHP calls it implode(), Javascript calls it Array.join(). Simply put, it returns a string consisting of the values of the array, with a delimiter in between the values.

Tag_string = Tags.join(', ')


2 thoughts on “Comma, Separated, Values,”

  1. Pingback: Accounting Basics

Leave a Reply