msgbartop
News, views, tips and tricks on Oracle and other fun stuff
msgbarbottom

ArrayDeleteAt Gotcha

Be careful when using ArrayDeleteAt. When an element is deleted, ColdFusion recalculates index positions. For example, in an array that contains the months of the year, deleting the element at position 5 removes the entry for May. After this, to delete the entry for June, you would delete the element at position 5 (not 6). Here is an example to demonstrate this behavior:

<cfset myArray = ArrayNew(1)>
<cfset myArray[1] = "Jan">
<cfset myArray[2] = "Feb">
<cfset myArray[3] = "Mar">
<cfset myArray[4] = "Apr">
<cfset myArray[5] = "May">
<cfset myArray[6] = "Jun">
<cfloop from="1" to="#ArrayLen(myArray)#" index="i">
    <cfset arrayDeleteAt(myArray,5)>
</cfloop>

If you execute the above, you get:

Cannot insert/delete at position 5.
The array passed has 4 indexes. Valid positions are from 1 to 4.


Filed in ColdFusion on 20 Jun 05 | Tags:


Reader's Comments

  1. |

    That’s why you should always loop backwards when performing deletes in an array:

    <cfloop from=”#ArrayLen(myArray)#” to=”1″ step=”-1″ index=”i”> <cfset arrayDeleteAt(myArray,5)> </cfloop>

  2. |

    Great tip Martin. Thanks.