Several times throughout the code, I want to print out a list of items, seperated correctly by a comma. Example:

Users browsing this thread: briantech, spinlock, bobjones, jamesgreer, nancyreagan

It would be painfully easy to just iterate through your array, printing out the array value followed by a comma. The problem with that though, is at the end of your list, your last element is going to have a comma at the end, which looks silly. So, instead you can just do this:

for ($i=0;$i < length($array);$i++)
{
     print $array[$i];
     if ($i+1 != length($array) )
          print ",";
}

This way it puts a comma after your value for every value except the last one.


2 Responses to “How to make a comma seperated list that looks nice”  

  1. 1 Josh Adams

    Alternatively, in Ruby:

    array.join(”, “)

  2. 2 chi

    Boy talk about being right. You can do that in php too… implode($array, “,”);

    I suck :(

Leave a Reply



 

Bad Behavior has blocked 72 access attempts in the last 7 days.