Associative Arrays

Associative arrays are arrays that map (or associate) a set of keys to a set of values. The data type of the keys need not be an integer, so descriptive strings, for instance, may be used. Keys must be unique, but need not be contiguous, or even ordered.

Declaration

Associative arrays are declared almost the same way as indexed arrays, with the difference that you must specify the data type of the key. For example:
ages as Int[String]

The code above declares an associative array named ages, which is of type Int and is indexed by string keys.

Initializing an array

You can use in-line arrays for initialization. They are similar to indexed arrays, but you must specify a key for each key-value pair, since the key is arbitrary:
ages as Int[String]
ages = ["John" : 23, "Peter" : 42, "Mary" : 29]

The code above initializes the array ages, associating the value 23 to the key "John", the value 42 to the key "Peter", and the value 29 to the key "Mary".

You can use keys to add elements to an existing associative array. For example:
ages as Int[String]
ages["John"] = 23
ages["Peter"] = 42
ages["Mary"] = 29

The code above also initializes the empty array ages, and then adds associated key-value pairs. The value 23 is assigned to the key "John", the value 42 to the key "Peter", and the value 29 to the key "Mary". If a key which already exists in the array is used again with a new value, this value replaces the old value for that key.

Accessing elements

The elements of an associative array can be accessed by key. The key is specified between square brackets, as an index would be for an indexed array:
ages as Int[String]
ages = ["John" : 23, "Peter" : 42, "Mary" : 29]

display ages["John"]

If you pass a nonexistent key, a null value is returned.

Ordered arrays

An associative array can be automatically ordered by key. To do so, the array must be declared using the ordered option before the index declaration, as follows:
ages as Int[ordered String]
The following example will result in an ordered array, even though the array keys are initialized out of order:
ages as Int[ordered String]
ages = ["John" : 23, "Peter" : 42, "Mary" : 29]
for key in ages do
    display key
end

The keys will be displayed in ascending order, using the key data type sort order, which in this case is alphabetical.