Associative Arrays
From PxPlus
Version 9 of PxPlus adds the ability to index/subscript arrays not only by index number but also by key word name. These type of arrays are commonly referred to as "Associative Arrays" or "Hash Tables".
Contents |
General Syntax
To reference an array by keyword, the standard subscript syntax is used except that instead of a numeric subscript a keyword subscript is used.
X$["Custid"] = "123456" X$["Name"] = "Little Bo-Peep Lambs Wool Inc" X$["Address"] = "123 Lost Her Way Lane"
Only a single dimension is supported. The keywords are limited to 255 bytes and may contain any character except $00$. Keywords are case insensitive thus "Custid", "custid", "CUSTID", and "CustID" are all considered the same.
Referencing an unknown key will return either a zero (if numeric array) or a null string (if a string array).
No upfront array declaration is needed, that is you do not need to issue a DIM to create an associative array and there is no predefined limit as to the number of elements an array can hold (apart from memory). Like normal arrays, the DIM(READ ...) function may be used to determine the number of elements in the array.
These arrays can also be passed to subroutines or used in IOLIST with the standard {ALL} syntax.
Internal Indexes
When elements are added to an associative array they are automatically assigned an index number. The first keyword will be assigned index number 1. Elements in the array can be referenced either by element number or keyword.
->begin ->X$["Custid"]="123456" ->print x$["CUSTID"] 123456 ->print x$[1] 123456
Associative arrays/Hash tables have a base index of 1 as opposed to normal arrays which generally are base zero.
To determine the internal index of a given keyword you can use the DIM(INDEX element) function. This function will return the index number for a given keyword or zero if not defined.
->print dim(index x$["CustID"]) 1 ->print dim(index x$["CustNO"]) 0
Using FOR to process all keywords
In order to simplify the processing of all element in an associative array, the INDEX option of the FOR directive has been enhanced to return the keyword for each element in an array.
The syntax is:
FOR strvar$ INDEX array
Where
- strvar$ is the variable to receive the keyword for each element in the array
- array is the array you wish to reference in the form variable{ALL}.
FOR process example
0010 BEGIN
0020 LET X$["Custid"]="123456"
0030 LET X$["Name"]="Little Bo-Peep Lambs Wool Inc"
0040 LET X$["Address"]="123 Lost Her Way Lane"
0050 FOR N$ INDEX X${ALL}
0060 PRINT "Key:",N$,@(20),X$[N$]
0070 NEXT
-:run
Key:Custid 123456
Key:Name Little Bo-Peep Lambs Wool Inc
Key:Address 123 Lost Her Way Lane
