KNOWLEDGE BASE
Tech Tip: Working with 2D Arrays
PRODUCT: 4D | VERSION: | PLATFORM:
Published On: November 24, 1999

An Array is essentially a series of variables that are related to each other somehow. For instance, suppose you had a list of addresses, and you wanted to store them in variables. You might easily write:

However, a better way to code this might be with an array:

ARRAY TEXT(aAddress;3) `a 3-element Text array

aAddress is a one-dimensional array. But how do you use a two-dimensional array? Suppose you had more than just a simple list of addresses - what if you had several lists of addresses, for various cities? A two-dimensional array will come in handy here.

ARRAY TEXT(aAddress2D;0,0) `an empty 2D array

The first element of a two-dimensional array is essentially just used as an Index Number for the second dimension of the array. There are not many commands that will work only on the first dimension of a two-dimensional arrays. However, INSERT ELEMENT will work:

INSERT ELEMENT(aAddress2D;0;3) `insert 3 arrays into our 2D Array

The aAddress2D array now holds 3 text arrays. Each array is referred to by its index number:

You will find that (almost) anywhere you use a one-dimensional array such as aAddress, you will be able to use the 2nd dimension of a 2D Array. For instance:

ARRAY TEXT(aCityList;0)

DISTINCT VALUES([People]City;aCityList)

\$iCityCount:=Size of array(aCityList)

ARRAY TEXT(aAddress2D;\$iCityCount;0) `size the 1st dimension to the # of cities

For (\$iCityNumber;1;\$iCityCount)
QUERY([People];[People]City=aCityList\$iCityNumber)
End for

And now how do you access the addresses for the city of San Jose? Something like this:

\$iCityIndex:=Find in array(aCityList;"San Jose")

If (\$iPos>0)

End for

End if

And now you know the basics of working with 2D Arrays!
Cut and Paste the following code example into your
own 4D project

---

---

---

---

---

---

---