Arrays in ASP
Now and then you have to store related items in arrays. I assume you are aware of their fundamental features of arrays, so I’m going to tell you how they are handled in ASP, in VBScript.
Suppose you want to find in alphabets, what month a date contains, that is, if you enter some date like "09/05/2002", the program should return "September." This program uses a one-dimensional array to store the names of all the months.
Before we proceed, let me mention that the same task can be achieved by using one of ASP’s in-built functions (we shall come to that later). I’m doing it in a longer way just to explain arrays.
The following program makes use of a me-defined function too, namely fetchmonth() that returns the character equivalent on the number month supplied to it as a parameter.
Let us first see the script:
<% Function fetchmonth(mNumber)
Response.Write "The day of the month in number is " & Month(Date()) & "<br>"
Response.Write "The day of the month is characters is " & fetchmonth(Month(Date())-1)
In VBScript, an array can be defined in more than one ways. One way I have shown above, that is, straightaway define the array like
<% Dim mArray(11) %>
After declaring the array (now that we have declared it), we fill values into it. Above we have entered months in individual index’s capacity. Using the array() function, this could have also been done like:
<% Dim mArray(11)
mArray=Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
If you want to know the size of an array, you can get it by
<% UBound(mArray) – LBound(mArray) + 1 %>
where UBound() returns the topmost index and LBound() returns the bottommost index. Of course LBound() should always return zero because all arrays in ASP have 0 (zero) as their first index. That’s why we have to add 1 to arrive at the numerical size of the array.
Our mArray, the one that contains months, has 12 items, because UBound(mArray) – LBound(mArray) means 11 – 0, and when you add 1 to it, it gives us 12.
We can change the size of an already existing array by using ReDim. So if we want to add 7 days of the week to our mArray, we first have to:
<% ReDim Preserve mArray(18) %>
and then fill it with days from mArray(12) onwards. If you noticed, I quietly used a word, "Preserve." If you don’t use Preserve, the size of the array is altered alright, but the old values are all gone. So if you want to use ReDim and re-size the array, use Preserve too.