Programmers - What method do you use to display comma seperated lists correctly?

In other words, when you want to put commas in between the values, but not at the end of the list, you have to have slightly different behaviour for a single iteration of your list (ie - last item, neglect the comma)

In PHP I’ve taken to doing it like this…

for($i = 0; $i < sizeof($the_array);$i++) echo ($i) ? “, $the_array[$i]” : “$the_array[$i]”;

This uses the unary operator to say "If this is the first time round the loop, display the value, otherwise display a comma then a space then the value.
So far this is the most code-compact way of doing it I’ve been able to come up with. Is there a more elegant way?

So that joins the values together with a comma? Is there a PHP equivalent? (I’ll google)

edit: Looks like there is one. I’ll use this in future :slight_smile:

http://php.net/manual/en/function.join.php

FWIW I just loop through and put everything into a string with my separator character(s) after, then trim the end of the resulting string of my character(s).

Two new things learned.

  1. the join function.

  2. The list I was displaying I had to append something to each item (specifically “°F”. I’m displaying temperatures stored as integers) so I learned that you can modifiy values in a foreach loop by adding a & to the variable like so…


foreach($low5 as &$temp) $temp .= " °F";

echo join(', ',$low5);


That might seem obvious to a seasoned PHP programmer. As a C/C++ programmer (years ago) I’m aware of passing by reference, it just hardly ever comes up in PHP)

I’ll bear this one in mind too. I had thought of cutting the last comma, but didn’t think of doing it with a string variable though. It might come in useful depending on the context.

If anyone’s interested, what I’m doing is following the excercises here - http://phpexercises.com/

They like to display lists using html’s ordered or unordered lists. But I prefer to display things with comma seperated values all on one line, in certain circumstances. I think it looks better in certain contexts.
“Yesterday I had bacon, eggs, sausage, black pudding”

As opposed to…

"Yesterday I had

bacon
eggs
sausage
black pudding"

the elegant way of doing this is having an appropriate method in your personal library of commonly used utility methods. Joining a list with a separator is indeed a really common thing, regardless of whether you code in PHP or whatnot. Doesn’t matter how you implement it - just don’t rewrite the code every time.

If you require the use of a personal library of utility functions in order to do a comma-join, it’s not elegant, and you’re doing it wrong.

That’s what I was thinking. Didn’t want to say anything though :slight_smile:

For Java there’s the Apache Commons Lang project that has StringUtils.join(…)

The problem with things like this is that it takes 4 seconds to write it from scratch correctly, but it takes 10 minutes to locate, understand and get working the utility version.

Lobsang, don’t try to make the most code-compact method, just do it the simplest most straight forward manner possible. Having a condition on the first time through the loop to avoid adding a comma is perfectly ok.

It will depend on the language and environment, but it’s not surprising to see the functionality directly coded instead of a call to a library function. Comments can make it perfectly clear what is happening. In general, all reasonable methods will operate around the same level of efficiency, and doing this at all should not be a performance critical operation. Recently I’ve seen more use of lists being defined with a leading comma to avoid this problem when the data is not for display: “,cat,dog,mouse”.

I’ll mention that while hacking and cursing my way through some horrible code today, I would not have been impressed to see an elegant solution for this trivial operation. There are far more important considerations in coding than this.

In Java I’d do something like:


String returnVal = "";

for(String item : list)
    returnVal += item + ",";

return returnVal.substring(0,returnVal.length - 1);


For extraneous spaces it’s even easier since you can use “returnVal.trim()”.

Edit: You can also do shenanigans with a non-enhanced for-loop and using a different print statement if i == list.size() - 1, but that gets messy, might as well just use substring.

Missed edit:

Writing a join operation (if I understand what it does correctly), isn’t too hard in Java (and I suspect in other languages either, but I don’t feel like making a Python version… a C version etc to find out).



// Precondition: list and delimiter are nonnull
// Postcondition: list will not be altered
public static String join(List<String> list, String delimiter){
  String returnVal = "";
  for(String item : list){
    returnVal += item + delimiter;
  }

  // Substring is first number inclusive, second number exclusive, so 
  //we don't need a -1.
  return returnVal.substring(0, returnVal.length() - delimiter.length());
}


If you want it to be even more general make List a list of Objects instead of Strings and just call toString() on item.

my personal library includes over a hundred methods, the join with separator one being one of them. This library exists in the several languages I have to deal with, such as PHP, Java, VB and C#, allowing me to write very similar code in any language I care about.

Sure beats figuring out how to do all sorts of common actions in any given language. One line of code and the list gets joined.

I assume the issue friedo has with your own personal library is that it only works for your own personal code.

Most code is developed in a setting with multiple developers and having each developer with their own personal library is not effective.

What have you gained over the very simple:



For ...
    if not first then append ","
    append element

return result


Absolutely nothing, but I think it looks nicer, and conceptually the use of a substring command is more intuitive.



String result = "";
for(int i = 0; i < list.size; i++){
  if(i != 0){
    result += ","
  }
  result += list.get(i)
}

return list

It’s not really any better, and I think the if statement is more confusing than just using substring, but it’s really no more than a personal preference option.

Edit: I’ve also only seen the comma added to the end:



String result = "";
for(int i = 0; i < list.size; i++){
  result += list.get(i)
   if(i != list.size - 1){
    result += ","
  }
}

return list

But that’s also just a function of from who and when you learned programming.

I should also mention that I like enhanced for loops, and it’s harder to use enhanced for loops with that method.

You either end up with things like

if (list.indexOf(item) != 0)

or things like

if (!list.get(0).equals(item))

The “if not the first element” method looks simpler and cleaner in pseudocode, but I think when it comes to Java implementation, the substring method looks simpler and cleaner.

I wonder – even though String uses StringBuilder internally to perform concatenations, would using StringBuilder directly improve performance?