Library code snippets

Iterate Arrays with For Each

The most common technique for iterating the contents of an array is to use a For Next loop and indicate the subscript for the array within the loop, like this:

<%
Dim strArray(3)

strArray(0) = "Paul"
strArray(1) = "John"
strArray(2) = "George"
strArray(3) = "Ringo"

Dim intCount
For intCount = LBound(strArray) To UBound(strArray)
   Response.Write strArray(intCount) & "<br>"
Next
%>

But another approach is to use a For Each loop. This technique doesn't require you to keep track on the subscript for each item, nor does it require you to interrogate the LBound and UBound on the array. This approach is shown below:

<%
Dim strArray(3)

strArray(0) = "Paul"
strArray(1) = "John"
strArray(2) = "George"
strArray(3) = "Ringo"

Dim strItem
For Each strItem in strArray
   Response.Write strItem & "<br>"
Next
%>

Comments

  1. 07 Apr 2003 at 18:07

    When using For Each to iterate through a multidimensional array, how do you reference the other items?

  2. 01 Jan 1999 at 00:00

    This thread is for discussions of Iterate Arrays with For Each.

Leave a comment

Sign in or Join us (it's free).

ElementK Journals

We'd love to hear what you think! Submit ideas or give us feedback