Home » Database » MS Access » How to use Associative Arrays in ASP

How to use Associative Arrays in ASP


First of all, You need to download the “Asp Associative Array class” then include the file “AssociativeArrayClass.asp” in your asp page.

Right now, You can start declaring associative arrays in ASP with the following syntax:

[sourcecode language=”vb”] Dim Person
Set Person = New AssociativeArray
Person("name") = "Max"
Person("surname") = "Vergelli"
Response.Write Person("name") & " " & Person("surname")
[/sourcecode]

In the above example, the key “name” in “Person” object, stores “Max” value. You can set strings or integers for the key and any object/variant type for the relative value. However, You can not set key with Null or “” strings like the following:

[sourcecode language=”vb”] ‘invalid keys…
Person(Null) = "Null Key"
Person("") = "Empty String"
Dim undefined
Person(undefined) = "Variable Not Initialized"
Response.Write Person("") & Person(Null) & Person(undefined)
[/sourcecode]

How to get every item of the associative array:
You can make a “For Each” loop on the array like in the following code


[sourcecode language=”vb”] For Each element In Person.Items
   Response.Write element.Key & " : " & element.Value & vbCrLf
Next
[/sourcecode]

“Person.Items” gets all the items inside the associative array and for each item You can get “Key” and “Value” properties.

How to copy an associative array:

[sourcecode language=”vb”] Dim Person_Clone             ‘it’s a Variant type
Set Person_Clone = Person    ‘NOTE: Use "Set" statement!
‘print values
Response.Write Person_Clone("name") & " " & Person_Clone("surname") & vbCrLf
‘get each key/value
For Each element In Person_Clone.Items
   Response.Write element.Key & " : " & element.Value & vbCrLf
Next
[/sourcecode]

How to create nested associative arrays…
You can create infinite nested associative arrays and accessing them like the following:

[sourcecode language=”vb”] Dim Person
Set Person = New AssociativeArray
Person("name") = "Max"
Person("surname") = "Vergelli"
Dim People
Set People = New AssociativeArray
People(1) = Person
People(2) = Person
People(3) = Person
Response.Write People(1)("name") & " " & People(1)("surname")
[/sourcecode]

Besides, You can enumerate all the keys/values inside the “People” associative array object

[sourcecode language=”vb”] For Each element In People.Items
   Dim el_person
   Set el_person = element.Value
   Response.Write el_person("name") & " : " & el_person("surname") & vbCrLf
Next
[/sourcecode]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.