For...Next Looping
Rated out of 5 stars (4.0833) - 24 Total Votes
This article will explain how to use "For...Next" and "For Each...Next" Looping!
There are times when looping with For..Next comes in handy, like populating a dropdown menu dynamically or setting a Boolean depending on if an item is in an array or collection. You can step through an Array or collection with the For..Next loop. We will cover the basics here
Lets say you want to add a number to the end of a string then we can do this
<% Dim i For i = 1 to 10 Response.Write "image"&i&"<br />" Next %>
If we run the code we get this:
image1
image2
image3
image4
image5
image6
image7
image8
image9
image10
If you only want to add even numbers to the string then we can use the Step method:
<% Dim i For i = 2 to 10 Step 2 Response.Write "image"&i&"<br />" Next %>
To get this:
image2
image4
image6
image8
image10
If you have an Array or collection you can loop through it using the For Each...Next Loop:
<% Dim x Dim colors(2) colors(0)="Red" colors(1)="White" colors(2)="Blue" For Each x in colors Response.Write x&"<br />" Next %>
Gives us this:
Red
White
Blue
We can check to see if a certain item is in the Array and print only that item:
<% Dim x Dim names(2) names(0)="Steve" names(1)="Jay" names(2)="Felicia" For Each x in names If x = "Jay" Then Response.Write x Exit For End If Next %>
Gives us this:
Jay
There is a lot you can do with For...Next looping and I encourage you to play around with it!
About the Author
Steve Frazier has been a classic ASP developer since 2003. He has developed CLASP applications for Fortune 500 companies and popular website's. He has also developed many ASP Scripts of his own! He is Web-master of HTMLJunction as well as its sister site - ASP Junction. He is currently working on a Web Portal that has the functionality of all the most popular Forums and Portals.