Arrays
An array is an ordered series of variables of the same type. Each variable is called an element of the array. An array is given its size when it is created; you can then resize it as many times as needed by adding, inserting, or deleting elements, or by resizing the array using the same command used to create it. Array elements are numbered from 1 to N, where N is the size of the array. An array always has a special element zero. Arrays are 4D variables. Like any variable, an array has a scope and follows the rules of the 4D language, though with some unique differences.
In most cases, it is recommended to use collections instead of arrays. Collections are more flexible and provide a wide range of dedicated methods. For more information, please refer to the Collection section.
Creating Arrays
You create an array with one of the array declaration commands from the "Array" theme. Each array declaration command can create or resize one-dimensional or two-dimensional arrays. For more information about two-dimensional arrays, see the two dimensional arrays section.
The following line of code creates (declares) an Integer array of 10 elements:
ARRAY INTEGER(aiAnArray;10)
Then, the following code resizes that same array to 20 elements:
ARRAY INTEGER(aiAnArray;20)
Then, the following code resizes that same array to no elements:
ARRAY INTEGER(aiAnArray;0)
Assigning values in arrays
You reference the elements in an array by using curly braces ({…}). A number is used within the braces to address a particular element; this number is called the element number. The following lines put five names into the array called atNames and then display them in alert windows:
ARRAY TEXT(atNames;5)
atNames{1}:="Richard"
atNames{2}:="Sarah"
atNames{3}:="Sam"
atNames{4}:="Jane"
atNames{5}:="John"
For($vlElem;1;5)
ALERT("The element #"+String($vlElem)+" is equal to: "+atNames{$vlElem})
End for
Note the syntax atNames{$vlElem}. Rather than specifying a numeric literal such as atNames{3}, you can use a numeric variable to indicate which element of an array you are addressing. Using the iteration provided by a loop structure (For...End for
, Repeat...Until
or While...End while
), compact pieces of code can address all or part of the elements in an array.
Important: Be careful not to confuse the assignment operator (:=) with the comparison operator, equal (=). Assignment and comparison are very different operations.
Assigning an array to another array
Unlike text or string variables, you cannot assign one array to another. To copy (assign) an array to another one, use COPY ARRAY
.