How do you loop over the values of an array?

An array is a collection of data indexed by numbers. So for an example, an array of values may have data at position 1, 2, and 3. In order to loop over the items in an array, the arrayLen() function should be used:

<!--- Arr is an array of values. --->
<cfloop index="x" from="1" to="#arrayLen(arr)#">
    <cfoutput>#arr[x]#</cfoutput>
</cfloop>

Generally this is safe code to write. However, it is possible that an array may have a missing position. Consider this array:

<cfset arr = arrayNew(1)>
<cfset arr[1] = "Jacob">
<cfset arr[3] = "Lynn">
<cfset arr[5] = "Noah">

Even though there is clearly only three items in the array, ColdFusion's arrayLen() function will return five.

This question was written by Raymond Camden
It was last updated on January 12, 2006.

Categories

Data Structures

Comments

comments powered by Disqus