Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

3.5. Manipulating Array Values

You want to access or modify specific elements within an array.


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]>


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 number—a 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
  <!---loop over array and display each element value--->
  • + Share This
  • 🔖 Save To Your Account