Home > Articles

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

This chapter is from the book

3.2. Adding an Element to an Array

You want to add an element to an array.

Technique

You add elements to an array by statically referencing the index of the element you want to insert, by using the ArrayAppend() function, or by using the ArrayPrepend() function.










<!---add element by index--->
<cfset aPetSounds[1] = "You Still Believe In Me">
<cfset aPetSounds[2] = "That's Not Me">

<!---add element using ArrayAppend--->
<cfset ArrayAppend(aPetSounds, "Don't Talk (Put Your Head On My Shoulder)")>

<!---add element using ArrayPrepend--->
<cfset ArrayPrepend(aPetSounds, "Wouldn't It Be Nice")>

Comments

After you've created an array, the natural next step is to populate its elements. (To create an array, see section 3.1, "Creating an Array.") One way to set the index value of a given element in an array is to reference the element you want to populate by index and set its value explicitly. This code is an example of creating a new array named aPetSounds and setting the first and second element to the strings "You Still Believe In Me" and "That's Not Me", respectively, by reference. (Pet Sounds, of course, is an album by the Beach Boys—often considered their masterpiece.)

Notice that ColdFusion uses 1-based numbering arrays—the first array element is in position 1. Many programming languages use 0-based numbering arrays, which place the first element in position 0.

Another way to add an element to an array is to use either the ArrayAppend() or ArrayPrepend() function. This method of adding elements ensures you don't place a value in an unintended index of the array.

ArrayPrepend() will prepend your value to the array, making it the first element and pushing all other elements down an index. This is a useful function if you need to add an element to the beginning of an array, but aren't worried about the other elements' index values. For example, in the previous technique, Wouldn't It Be Nice gains an index of 1, whereas You Still Believe In Me and That's Not Me now have index values of 2 and 3, respectively (even though their index values were given explicitly).

ArrayAppend() adds your element to the end of an array, making it the last element in the array, and leaving the other elements where they are. Use the ArrayAppend() function when you need to maintain the integrity of the array's current index. Notice that Don't Talk (Put Your Head On My Shoulder) is now a part of the petSounds array, but it has simply been "tacked on," and has an index value of 4. This leaves the first three song titles' index values untouched.

  • + Share This
  • 🔖 Save To Your Account