Well, I would divide this into 3 camps:
1. Build the string with the necessary commas only
2. Use comma prefixed before each item and finally use SUBSTR from the second position.
3. Add items with ccomma suffix and finally remove the surplus comma with LEFT() or RTRI/TRIM.
Assume there is a dbf or curssro alias items with an item field that's varchar and so has trimmed items (no trailing spaces as you have with a normal char field).
1. with IIF
Code:
Local lcCSV
lcCSV=''
Select items
scan
lcCSV = m.lcCSV+IIF(lcCSV=='','',',')+items.item
endscan
2. prefix and SUBSTR
Code:
Local lcCSV
lcCSV=''
Select items
scan
lcCSV = m.lcCSV+','+items.item
endscan
lcCSV = Substr(m.lcCSV,2)
3. suffix and TRIM
Code:
Local lcCSV
lcCSV=''
Select items
scan
lcCSV = lcCSV+items.item+','
endscan
lcCSV = RTRIM(m.lcCSV,',')
And all of them have their negative point.
1. An IIF for every item
2. and 3: A final string operation.
But it's also pointless to rant about this necessary last operation in case 2 and 3, as every item you append with the assignment lcCSV = lcCSV + does nneed to allocate enough memeory for the overall string, and copies over lcCSV plus the item into it. VFP has no thing like C#'s stringbuilder class. And though VFP is programmed in C++ it also has no pointer to do tricks with, at least you don't have hands on it within VFP itself. There also isn't a function like PHPs implode().
There are surely more ways to do it
4. like 1, but without IIF:
Code:
Local lcCSV, lcSeparator
Store '' To lcCSV, lcSeparator
Select items
scan
lcCSV = m.lcCSV+lcSeparator+items.item
lcSeprator = ','
endscan
Now there's no IIF, but an assignment that would be suffiient, if it's done once instead of every iteration
5. like 1 but through special handling of first element
Code:
Local lcCSV
Select items
Go Top
lcCSV = items.item
Skip 1
Scan Rest
lcCSV = m.lcCSV+','+items.item
Endscan
Now you can play with these and special cases like extremely many items or no items at all, etc. etc.
But you can't tell me that you can't think of any way on your own, at least to create the string with a surplus comma at the start or end. And then it's really just a short visitation of the help to look up how to get substrings, which functions exist for that, like LEFT, RIGHT, SUBSTR, or how you can use TRIM/RTRIM/LTRIM/ALLTRIM. Also ALLTRIM allows specifying other characters to trim away than whitespace.
It does really not play any mentionable role to do things the one or other way. If you have extremely many elements it would turn out to be better to create partial lists and concatenate them as a last step. If you have 1 million elements you would make 999.999 copies in average half the string length, and that would hurt the performance, but it would be a problem no matter which of the three major methods you choose. And the last step to remove the comma will never be a major part of the operation.
Chriss