IT SOLUTIONS
Your full service technology partner! 
-Collapse +Expand
To/From Code
   ► KBTo/From GuidesReferenceData Structures  Print This     

Associative Array (Cross Ref > Data Structures)

Associative Array

A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'

Languages Focus

Associative arrays are also known as a dictionary or a hash table in other languages.

Access VBA:   Collection

In addition to Add and Item, collections also offer Count and Remove. Notice that Add uses the format of Value, Key (which is backwards from many other languages).

Syntax Example:
Dim States As New Collection
   
States.Add "California", "CA"
States.Add "Nevada", "NV"
    
MsgBox (States.Item("CA"))

 

More Info

Code:  Access VBA Associative Array (Collection)
Definition:  Associative Array

ASP Classic:   Scripting.Dictionary

Use the scriptiing dictionary object which is available on later versions of ASP Classic (all still commonly in use).

Note: Both Access VBA and VB Classic use a collection for this but collections are not supported in ASP Classic.

Syntax Example:
Dim StateList
 
set StateList = Server.CreateObject("Scripting.Dictionary")
StateList.Add "CA", "California"
StateList.Add "NV", "Nevada"
 
Response.Write "I live in " & StateList.Item("CA")

Looping Through An ASP Dictionary

Here's some code that adds a few items to a dictionary and then loops through them using a for each loop.

Dim StateList
Dim Key
  
set StateList = Server.CreateObject("Scripting.Dictionary")
 
StateList.Add "CA", "California"
StateList.Add "NV", "Nevada"
StateList.Add "FL", "Florida"
 
For Each Key in StateList
  Response.Write Key & " is " & StateList(Key) & "<br>"
Next

Here's one more example showing how to loop through Request.QueryString. Just to show you that you can.

Dim Key
 
For each Key in Request.QueryString
 Response.Write Key & "=" & Request.QueryString(Key)
Next

Exists and Remove

Use Exists to check if a key is in the associative array and Remove to delete it. It's a good idea to check if an element exists prior to deleting it. Here's how:

If StateList.Exists("FL") Then
    StateList.Remove("FL")
End If

If you fail to check if an element exists and it doesn't, you will get the following error:

Microsoft VBScript runtime  error '800a802b'
Element not found
/path/yourpage.asp, line 51

Sorting

No built-in sort function. However, Microsoft provided a good example of how to do this at http://support.microsoft.com/kb/246067.

More Info

Code:  ASP Classic Associative Array (Scripting.Dictionary)
Definition:  Associative Array
FAQ:  Associative Arrays in ASP Classic

C#:   Dictionary

Syntax Example:
//using System.Collections.Generic;
 
Dictionary <String, String> airports = new Dictionary <String, String>();
airports.Add("LAX", "Los Angeles"); 
airports.Add("SFO", "San Francisco");
airports.Add("SAN", "San Diego");
MessageBox.Show(airports["LAX"]);

 

More Info

Definition:  Associative Array
Code:  C# Associative Array (Dictionary)

C++:   map

Syntax Example:
map<string, int> mymap;
mymap.insert(AValuePair);


About Associative Array
A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'

More Info

Definition:  Associative Array
Code:  C++ Associative Array (map)

Corel Paradox:   DynArray

In ObjectPAL associative arrays are known as dynamic arrays.

Syntax Example:
var
myDynArray   DynArray[] String
endVar

 
myDynArray["Last_Name"] = "Spitz"
myDynArray["First_Name"] = "Randy"
myDynArray.view()

More Info

Code:  Assocative Arrays in ObjectPAL
Definition:  Associative Array
Code:  ObjectPAL Associative Array (DynArray)

Delphi:   TStringList Assoc Array

Object Pascal doesn't have a native associative array, but you can use a TStringList the same way. (Alternatively, search the Internet for TStringHash and THashedStringList classes for implementations of a true associative array).

Syntax Example:
var
  StateList : TStringList;
begin
StateList := TStringList.Create; 
  StateList.CommaText := 'CA=California, FL=Florida';
  ShowMessage('FL is ' + StateList.Values['FL']);
end;


About Associative Array
A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'

More Info

Definition:  Associative Array
Code:  Associative Arrays in Delphi/Object Pascal (Use TStringList)

More Info

Code:  Assocative Arrays in ObjectPAL
Definition:  Associative Array
FAQ:  Associative Arrays in ASP Classic
Tip:  Associative Arrays in Delphi/Object Pascal
Code:  Associative Arrays in JavaScript

Java:   HashMap()

An associative array links a set of keys to a set of values. In Java, associative arrays are implemented as Maps.

This will print "Arizona."

Syntax Example:
import java.util.*;

public class Maps
{
    public static void main(String[] args)
    {
        Map states = new HashMap();
       
        states.put("CA", "California");
        states.put("FL", "Florida");
        states.put("AZ", "Arizona");

        System.out.println(states.get("AZ"));
    }
}


About Associative Array
A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'

More Info

Definition:  Associative Array
Code:  Associative Arrays in Java (a Map)


More Info

Code:  Assocative Arrays in ObjectPAL
Definition:  Associative Array
FAQ:  Associative Arrays in ASP Classic
Tip:  Associative Arrays in Delphi/Object Pascal
Code:  Associative Arrays in Delphi/Object Pascal (Use TStringList)

JavaScript:   Array(), use [

Syntax Example:
var MyStateList= new Array()
MyStateList["CA"]="California";
MyStateList["OR"]="Oregon";
Alert("OR is " + MyStateList["OR"])


About Associative Array
A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'

More Info

Definition:  Associative Array
Code:  Associative Arrays in JavaScript

More Info

Code:  Assocative Arrays in ObjectPAL
Definition:  Associative Array
FAQ:  Associative Arrays in ASP Classic
Tip:  Associative Arrays in Delphi/Object Pascal
Code:  Associative Arrays in Delphi/Object Pascal (Use TStringList)

Perl:   % Array Preface

Syntax Example:
my %weekdays = (
'Sun' => 'Sunday',
'Mon' => 'Monday',
'Tue' => 'Tuesday',
'Wed' => 'Wednesday',
'Thu' => 'Thursday',
'Fri' => 'Friday',
'Sat' => 'Saturday',
);
my $day_of_the_week = $weekdays{'Mon'};

 

More Info

Definition:  Associative Array
Code:  Perl Associative Array (% Array Preface)

PHP: 

Declare associative array with initial known values. You can also add to associative array. (You can just assign values without ever declaring it too!)

Syntax Example:
$prices = array( 'Tires'=>100, 'Spark Plugs'=>4 );
$prices['Oil'] = 10;
 
echo "Tires=" . $prices['Tires'] . "<br>";
echo "Oil=" . $prices['Oil'] . "<br>";

About Associative Array
A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'

Complete Example

Here is a complete example:

<html>
<head><title>PHP Hello World Example</title></head>
 
<body>
<?PHP
//Declare associative array with initial known values.
$prices = array( 'Tires'=>100, 'Spark Plugs'=>4 );
 
//Add to associative array. (You can just assign values without ever declaring it too!)
$prices['Oil'] = 10;
 
//Usage Example 1
echo "<br><br>Example 1<br>";
echo "Tires=" . $prices['Tires'] . "<br>";
echo "Oil=" . $prices['Oil'] . "<br>";
 
//Usage Example 2 - foreach loop with $key and $value
echo "<br><br>foreach loop<br>";
 
foreach ($prices as $key => $value)
 echo $key.'=>'.$value.'<br />';
//
//Clear it for another use.
//
echo "<br><br>reset example<br>";
reset($prices);
 
$prices['Computer'] = 700;
$prices['monitor'] = 200;
$prices['mouse'] = 15;
 
foreach ($prices as $key => $value)
  echo $key.'=>'.$value.'<br />';
?>
 
</body>
</html>

More Info

Definition:  Associative Array
Code:  PHP Associative Array

VB Classic:   Collection

In addition to Add and Item, collections also offer Count and Remove. Notice that Add uses the format of Value, Key (which is backwards from many other languages).

Syntax Example:
Dim States As New Collection
   
States.Add "California", "CA"
States.Add "Nevada", "NV"
    
MsgBox (States.Item("CA"))

 

More Info

Definition:  Associative Array
Code:  VB Classic Associative Array (Collection)

VB.Net:   Dictionary

An associative array links a set of keys to a set of values. In Visual Basic, associative arrays are implemented as Dictionaries.

This code produces a message box saying "Nevada."

Syntax Example:
//Imports System.Collections.Generic
Dim States As New Dictionary(Of String, String)

States.Add("CA", "California")
States.Add("NV", "Nevada")
 
MsgBox(States("NV"))


About Associative Array
A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'



Linked Certification Question(s)

The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

Intermediate

1 Intermediate Level Question

Question #1: Multiple Choice

Which code snippet is the correct syntax for declaring and using an associative array?

Answer:
1. 
//Imports System.Collections.Generic
Dim States As New Collection

States.Add("CA", "California")
States.Add("NV", "Nevada")
 
MsgBox(States("NV"))
2. 
//Imports System.Collections.Generic
Dim States As New _
Dictionary(Of String, String)

States.Add("CA", "California")
States.Add("NV", "Nevada")
 
MsgBox(States("NV"))
3. 
//Imports System.Collections.Generic
Dim States As New _
Collection(Of String, String)
  
States("CA") = "California"
States("NV") = "Nevada"
 
MsgBox(States.Item("NV"))
4. 
//Imports System.Collections.Generic
Dim States As New Collection(Of String)

States.Add("CA", "California")
States.Add("NV", "Nevada")
 
MsgBox(States.Item("NV"))
5. 
//Imports System.Collections.Generic
Dim States As New Array(String, String)

States.Add("California", "CA")
States.Add("Nevada", "NV")
 
MsgBox(States.ListItem("NV"))

More Info

Definition:  Associative Array
Code:  Associative Arrays in Visual Basic (a Dictionary)
 


More Info

Code:  Assocative Arrays in ObjectPAL
Definition:  Associative Array
FAQ:  Associative Arrays in ASP Classic
Tip:  Associative Arrays in Delphi/Object Pascal
Code:  Associative Arrays in Delphi/Object Pascal (Use TStringList)




Go ahead!   Use Us! Call: 916-726-5675  Or visit our new sales site: 
www.prestwood.com


©1995-2024 Prestwood IT Solutions.   [Security & Privacy]