- 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.5. Manipulating Array Values
You want to access or modify specific elements within an array.
Technique
Manipulate elements in a populated array by iterating over the array and performing the desired function during each iteration of the loop.
<!---Manipulate each element to append song number---> <cfloop from="1" to="#ArrayLen(aPetSounds)#" index="i"> <cfset aPetSounds[i] = "Song " & i & ": " & aPetSounds[i]> </cfloop>
Comments
Arrays are used in Web applications to store ordered collections of related data. Naturally, as a user progresses through an application, data will change. Therefore, you need a way to manipulate the values of an array in order to perform functions on element values.
Say you need to add the track number to each value in the aPetSounds array. You can do so by looping over the array values and manipulating the string to include the loop number, resulting in the desired value.
Notice in the first cfloop statement that the value of the current element is referenced and a new value is set in the same line. This inline variable manipulation is acceptable in CFML. You also use the index variable i to insert the song numbera simple example of benefiting from the order functionality provided by the array data type.
To display the new values with the track number prepended to the value, execute the following code:
Pet Sounds Track Listing <hr> <cfoutput> <!---loop over array and display each element value---> <cfloop from="1" to="#ArrayLen(aPetSounds)#" index="i"> #aPetSounds[i]#<br> </cfloop> </cfoutput>