Skip to main content
July 14, 2007
Answered

How to loop through token values

  • July 14, 2007
  • 4 replies
  • 493 views
I'm trying to create a simple loop that runs through a bunch of comma delimted values in a string and adds them together. What is the best way to do this?

Currently, my code looks something like this

<cfset basevalue = "0">
<cfset count = "1">
<cfset token = getToken(myString,count,",")>
<cfloop condition = "token NEQ NULL">
<cfset token = getToken(myString,count,",")>
<cfset basevalue = basevalue + token>
<cfset count = count + 1>
</cfloop>

This doesn't seem to be working. Any ideas?
This topic has been closed for replies.
Correct answer Sankalan
I think the correct syntax is index="token". If you have some other delimiter then,

<cfset thesum = 0>
<cfloop list="#mystring" index="token" delimiters="yourDelimiter ">
<cfset thesum = thesum + token>
</cfloop>

Thanks

4 replies

BKBK
Community Expert
Community Expert
July 14, 2007
Oh, and, another thing. if your list is going to contain blank elements, like "1,2,3,,4,5", then it will be advisable to apply arrayToList() first.

SankalanCorrect answer
Participating Frequently
July 14, 2007
I think the correct syntax is index="token". If you have some other delimiter then,

<cfset thesum = 0>
<cfloop list="#mystring" index="token" delimiters="yourDelimiter ">
<cfset thesum = thesum + token>
</cfloop>

Thanks
Inspiring
July 14, 2007
This is equally simple.
<cfset thesum = 0>
<cfloop list="#mystring" item="token">
<cfset thesum = thesum + token>
</cfloop>
July 14, 2007
quote:

Originally posted by: Dan Bracuk
This is equally simple.
<cfset thesum = 0>
<cfloop list="#mystring" item="token">
<cfset thesum = thesum + token>
</cfloop>

How does this know what the token is? By that I mean what the delimiter is?

Inspiring
July 14, 2007
quote:


How does this know what the token is? By that I mean what the delimiter is?


The default delimiter is a comma, which you specified in your original post.
BKBK
Community Expert
Community Expert
July 14, 2007
to create a simple loop that runs through a bunch of comma delimted values in a string and adds them together

Here is a much simpler way to add the elements of a list:

<cfset arr=listToArray(myString)>
<cfset sum=arraySum(arr)>