Go to: Articles List

Looping Logic Part 4 : For Each...Next Statements
Part 1 | Part 2 | Part 3 | Part 4

     The For Each...Next loops (FEN loop) are very different from the do, while, and for next loops. The FEN loop is used to loop through collections like recordsets, form collections, or arrays.

     You can think of a collection as storage facility. The ones that allow you to rent a place to store things you can't find a place for. Each storage facility has certain number of units available.

     Going with this example, let's assume we have an object that represents our storage facility (objStorage). And we want to print out the name of each customer in our facility. Here is some code that could do this:

For Each Unit in objStorage
Response.Write("Unit #" & Unit.Number & " -- Name: " & Unit.CustName & "<br>")

Ok, this might have been a little hard to understand. How about an example that you can try yourself. Here is an example of looping through the server variables (you can cut and paste this code in to a file, save it, and run it from an asp capable server to see the result).

For Each x in Request.ServerVariables
     Response.Write(x & " = " & Request.ServerVariables(x) & "<br>")

I cut and pasted a few of the server variables that I got back. There is a big list that comes back, not just these.

HTTP_ACCEPT = image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*
HTTP_HOST = www.Brinkster.com
HTTP_USER_AGENT = Mozilla/4.04 [en] (Win95; I)

There is no signifigance in the x. We really could have called this anything that we wanted to. I choose x because it is easy to work with and a commonly used variable name.

You can learn more about Server Variables in the Server Variables How To.