Friday, June 01, 2007

ListToArray with empty elements

Recently there was a request on our forum to support empty elements in ListToArray function for Scorpio i.e ColdFusion 8. it might not be done in Scorpio since it is too late to add a new function. However it can be very easily achieved in cfm itself. Here is the code to do it.

<cfset cflist="a,b,,c,,,d">
<cfset cfarr1 = ListToArray(cflist)>

<cfset cfarr2 = cflist.split(",")>
<cfset cfarr2 = cflist.split(",", -1)>

<cfdump var="#cfarr1#">
<cfdump var="#cfarr2#">

for(i=1; i <= ArrayLen(cfarr2); i++)
writeoutput("Element #i# : #cfarr2[i]# <br>");

As you can see, 3rd, 5th and 6th element in this cfarr2 are empty.


charlie griefer said...

hi rupesh:

i blogged this a little while back (, and it was pointed out (accurately) in the comments that this method won't work if the LAST list element is empty.

any workaround for that?


charlie griefer said...

ok let's try that again with a tinyurl :)

Rupesh Kumar said...

oh ya.. you are right.. split() does not consider the empty elements at the end of the list.

Since split() takes a regular expression, I think it should be possible to get it right. As I am not an expert in reg-ex, I tried doing it regular way and will post it in a separate post. I will ask some reg-ex experts in the team if we can get a simple reg-ex for this.

Rupesh Kumar said...

I posted another entry here which has an UDF which does the same.

Rupesh Kumar said...

Thanks to Andrew Clark for the tip that split(",", -1) does the trick. Changed the code above to use the correct method which takes care of empty elements in the list.

The Luxes said...

When I tried your code, I get this error:

The selected method split was not found. Either there are no methods with the specified method name and argument types, or the method split is overloaded with arguments types that ColdFusion can't decipher reliably. If this is a Java object and you verified that the method exists, you may need to use the javacast function to reduce ambiguity.

Will this work on CF 7?

Rupesh Kumar said...

You are right.. Somehow split(",", -1) works on ColdFusion 8 but not on 7.

It will work fine if you change that to
split(",", javacast("int", -1))

Let me know if that works for you.