How should a two-dimesional array with unknown number of rows be declared?
Hi,
I am just wondering how I should declare a two-dimensional array in VB-script when I don't know how many rows I will use. Assume for example that I want to store some people's first names and last names. Then I would write:
Dim peopleArray(2, 10)
Assuming not more than 11 people will be stored, but how should I write the array declaration if I don't know how many rows I will need in advance? Is there maybe a way to make the array expand itself dynamically?
Hope someone can take a minute (or two ) and explain to me.
You should be able to declare the array like Dim peopleArray(2, 1). When you need to adjust the size of the array, you can use the ReDim statement. (this will only re-dimension the right side of the array, though. I hope that is not a problem.
Code:
' The Preserve keyword allows us to preserve the data currently in the array.
ReDim Preserve peopleArray(2, 2)
If this does not solve the problem, try explaining in a bit more detail so we can try to come up with an alternate solution.
My two-dimensional array problem, hopefully more explicit...
Thanks for your help with the "ReDim" and "Preserve". I guess I need to figure out how they are used in practice. My main concern is how I should use them in this code to make it possible for the array (and application variable) to expand dynamically when the declared number of rows (10) have been reached without losing the earlier stored entries and without setting the number of rows to 10 000+ to have some margin?
I have chosen to store the first name and last name, which are retrieved from a form, in an application variable. I know that it might be smarter to store the names in a database instead but I am still interested how to handle this situation (everyone may not have access to Access). Hope one of you guys can look it over...
<%@ language = VBscript%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
'Lock application and then create (if no records exist) or retrieve the array from application variable
If not isArray( Application ("peopleArray")) Then
DIM namesArray (2,10)
ELSE
Application.Lock
namesArray = Application ("peopleArray")
End if
'Retrieve entered names in the form (another URL)
firstname = Request.Form ("textfield1")
lastname = Request.Form ("textfield2")
'Add a person's first+last name to the namesArray at the first empty row
For i=0 to UBOUND(namesArray, 2)
If namesarray (FNAME, i) = "" Then
namesarray(FNAME, i) = firstname
namesarray(LNAME, i) = lastname
End if
Exit for
%>
</head>
<body>
Thank you for your interest. Here is a list of all members.
'Write all first+last names stored in the array.
<%
For i=0 to UBOUND(namesArray, 2)
%>
<br>
<%=namesarray (FNAME, i)%>
<%=namesarray (LNAME, i)%>
<%
Exit for
' Update application variable with array
Application ("peopleArray") = namesArray
Application ("peopleArray").Unlock
%>
Bookmarks