Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap

Q3007 How can I break up a list of strings into separate variables?

You are here: irt.org | FAQ | ColdFusion | Q3007 [ previous next ]

The exact question: "I am passing multiple selections from a select box. The output is comma delimited strings (i.e.. test1, test2, test3) which is treated as one variable. How can I format this output so that it can be treated as three separate variables (or however many is selected)."

ColdFusion has a whole set of list functions available that make it easy to work with delimited lists. Here is an example.

Suppose we have a form that was submitted with a multiple select box. The select box name is mySelect. Three values were selected, so the string passed is "test1,test2,test3". To refer to each individual item, we can use the ColdFusion ListGetAt() function:

ListGetAt(list, position [, delimiters])

where "list" is the name of the string, "position" indicates the position of the element being retrieved, and "delimiters" (optional) indicates the character(s) used to delimit the string (default is comma). So, in our example, we could retrieve the three strings by saying:

ListGetAt(form.mySelect, 1,",")
ListGetAt(form.mySelect, 2)
ListGetAt(form.mySelect, 3)

BUT, what if we don't know how many items are going to be selected? We can use CFLOOP to iterate through each item in the list.

<cfloop list="#mySelect#" index="listItem">	<cfoutput>#listItem#</cfoutput><br>

To take it one step further, we can use these functions to create an array of variables:

<cfset myArray = ArrayNew(1)>
<cfloop from="1" to="#ListLen(form.mySelect)#"index="listCount">
    <cfset myArray[listCount] =ListGetAt(form.mySelect,listCount,",")>
	<cfoutput>myArray[#listCount#] =#myArray[listCount]#</cfoutput><br>

In this case, we change the loop from a CFLOOP LIST= loop to a CFLOOP FROM/TO, so that we could use the index variable as our array counter. Also, we use the ListLen() function to determine the number of items in the list. Run this example, it will create the array, and display each array element as it goes through the loop.

©2018 Martin Webb