Associative array (AA) - is an array which elements are accessed by associated character strings. Let's consider associative array in contrast of an ordinary array. An ordinary array may be written as follows:
declare m m=11; m=12; ....
To get access to elements, a consecutive numbers set is used, and it is limited with the array size. Inserting a new element becomes a problem, and it results in time losses. Opposite to ordinary arrays, elements of association arrays are identified by strings. map() function creates an empty associative array. New elements are added to the associative array automatically. To get access to the element of the associative array object-style syntax can be used. For example:
// create an empty associative array m=map() // add two elements m:asdf=11; m:qwer=12 ? valtype(m) // 'O' (object) ? len(m) // 2 ? m:qwer // 12
To be honest, elements of associative array are identified by a hash codes of strings. Hash code is the number as a result of hashing a string to a number by using bit operations. For strings of less than 20 characters, the probability of coincidence of hash codes is approximately 1/1000000. For longer strings, the probability is increased.
The compiler calculates hash codes of strings enclosed in "`" characters. For example:
? m:qwer == m[`qwer`] // .t.
Also, compiler calculates hash codes of strings with hash_ prefix. In this case, the string is not converted to upper case. You should do it yourself:
? m:qwer == m[hash_qwer] // .f. ? m:qwer == m[hash_QWER] // .t.
At run time, hash code can be calculated by hashstr() function:
? m:qwer == m[hashstr("QWER")] // .t.
Pay attention to QWER which is written in upper case, because compiler does not distinguish letter cases.
It's possible to get a list of indexes in the associative array by mapkeys() function which returns an ordinary array with hash codes of associative array elements:
mm := mapkeys(m) ? len(mm) // 2 for i to len(mm) ? mm[i] // something like 1233345677, 124321423 next
Also, the associate array is characterized by a very fast access to elements, because necessary element is actually searched in a hash table.