- Introduction
- Creating an Array
- Adding an Element to an Array
- Displaying a Value in an Array
- Looping over an Array
- Manipulating Array Values
- Sorting an Array
- Multidimensional Arrays
- Creating Arrays with More Than Three Dimensions
- Array Aggregate Functions
- Array Utility Functions
- Array Information Functions
3.4. Looping over an Array
You want to iterate over each element in an array.
Technique
Use <cfloop> to iterate over each element in an array.
Pet Sounds Track Listing <hr> <cfoutput> <!---loop over array and display each element value---> <cfloop from="1" to="#ArrayLen(aPetSounds)#" index="i"> Song #i#: #aPetSounds[i]#<br> </cfloop> </cfoutput>
Comments
This example revisits the aPetSounds array and loops from 1 to the length of the array to extract and display the value of each element. Looping over an array to display its values ensures that you won't reference an index that doesn't exist. This code also shows that you can use ColdFusion expressions and variables to reference indexes within an arrayin this case, you use the current index of the loop to retrieve the associated index in the array.
NOTE
This code introduces the ArrayLen() function. ArrayLen() accepts a single argument: the array in question. Similar to the Len() function, which counts the number of characters in a string, ArrayLen() returns the number of elements in an array.