Concept

# Arrays

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Description

Arrays are an indexed collection of data for a specific data type. The index of an array begins at zero. The maximum index value is 2,147,483,646. <span class="title-ref">Arrays</span> themselves are not a data type, but any data type can be defined as an array using the Var statement or as a property.

## Usage

``` xojo
Var arrayName() As dataType
Var arrayName(size [, size2,...sizeN ]) As dataType
Var arrayName(), arrayNameN() As dataType [ = Array(value1, value2, ..., valueN) ]
```

| Part            | Type               | Description                                                                                          |
|-----------------|--------------------|------------------------------------------------------------------------------------------------------|
| arrayName       | Variable name      | The name of the array.                                                                               |
| size            | Integer            | Optional: The size of the array. Size must be integer literals or integer constants.                 |
| sizeN           | Integer            | Optional: The size of the next dimension of the array if you are creating a multi-dimensional array. |
| dataType        | Data type or class | The data type or class of the array.                                                                 |
| value1...valueN | values             | Values that match the dataType to add to the array.                                                  |

## Methods

<div class="rst-class">

table-centered_column_4

</div>

| Name                            | Parameters                                                                                            | Returns                            | Shared |
|---------------------------------|-------------------------------------------------------------------------------------------------------|------------------------------------|--------|
| `Add<arrays.add>`               | item As DataType                                                                                      |                                    |        |
| `AddAt<arrays.addat>`           | index As `Integer</api/data_types/integer>`, item As DataType                                         |                                    |        |
| `Array<arrays.array>`           | value1 As DataType, \[valueN As DataType\]                                                            |                                    |        |
| `Count<arrays.count>`           | `Optional</api/language/optional>` index As `Integer</api/data_types/integer>`                        | `Integer</api/data_types/integer>` |        |
| `Dimensions<arrays.dimensions>` |                                                                                                       | `Integer</api/data_types/integer>` |        |
| `FirstIndex<arrays.firstindex>` |                                                                                                       | `Integer</api/data_types/integer>` |        |
| `IndexOf<arrays.indexof>`       | item As DataType, `Optional</api/language/optional>` startIndex As `Integer</api/data_types/integer>` | `Integer</api/data_types/integer>` |        |
| `LastIndex<arrays.lastindex>`   | `Optional</api/language/optional>` dimension As `Integer</api/data_types/integer>`                    | `Integer</api/data_types/integer>` |        |
| `Pop<arrays.pop>`               |                                                                                                       | ArrayType                          |        |
| `RemoveAll<arrays.removeall>`   |                                                                                                       |                                    |        |
| `RemoveAt<arrays.removeat>`     | index As `Integer</api/data_types/integer>`                                                           |                                    |        |
| `ResizeTo<arrays.resizeto>`     | newSize As `Integer</api/data_types/integer>`                                                         |                                    |        |
|                                 | index As `Integer</api/data_types/integer>`, newSize As `Integer</api/data_types/integer>`            |                                    |        |
| `Shuffle<arrays.shuffle>`       |                                                                                                       |                                    |        |
| `Sort<arrays.sort>`             |                                                                                                       |                                    |        |
|                                 | `AddressOf</api/language/addressof>` methodName                                                       |                                    |        |
| `SortWith<arrays.sortwith>`     | array1 As `Array</api/language/array>`, \[arrayN As `Array</api/language/array>`\]                    |                                    |        |

## Method descriptions

<div id="arrays.add">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.Add

**Add**(item As DataType)

> Adds a new element to the end of a one-dimensional array, increasing the size of the array by one. The item must match the data type of the array.
>
> The Add method works with one-dimensional <span class="title-ref">Arrays</span> only.
>
> This example adds a new element to the end of the names array. The new element becomes the last element of the array.
>
> ``` xojo
> Var names() As String
> names.Add("Betty")
> ```

<div id="arrays.addat">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.AddAt

**AddAt**(index As `Integer</api/data_types/integer>`, item As DataType)

> Adds a new element into an array at the specified *index*.
>
> The AddAt method works with one-dimensional <span class="title-ref">Arrays</span> only.
>
> Consider the array *names* defined as follows:
>
> ``` xojo
> names = Array("Leonard", "Abraham", "Herbert")
> ```
>
> The statement:
>
> ``` xojo
> names.AddAt(2, "Bill")
> ```
>
> Because the index of an array begins at zero, the result would be:
>
> |         |
> |---------|
> | Leonard |
> | Abraham |
> | Bill    |
> | Herbert |

<div id="arrays.array">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.Array

**Array**(value1 As DataType, \[valueN As DataType\])

> Assigns a list of values to consecutive elements of a one-dimensional array.
>
> The following statements initialize the array using separate assignment statements for each array element:
>
> ``` xojo
> Var names(2) As String
> //using separate assignment statements
> names(0) = "Fred"
> names(1) = "Ginger"
> names(2) = "Stanley"
> ```
>
> The following statements use the Array function to accomplish the same thing. Note that you don't have to declare the exact size of the array in the `Var</api/language/var>` statement. The Array function will add elements to the array as needed.
>
> The following statement creates and populates the first three elements of the array *aNames*.
>
> ``` xojo
> Var names() As String
> ' using the Array function
> names = Array("Fred", "Ginger", "Stanley")
> ```

<div id="arrays.count">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.Count

**Count**(`Optional</api/language/optional>` index As `Integer</api/data_types/integer>`) As `Integer</api/data_types/integer>`

> Returns the number of rows in the array. For multi-dimensional <span class="title-ref">Arrays</span>, the number of rows in a specific dimension will be returned if the dimension is passed.
>
> This example displays the number of rows in the array:
>
> ``` xojo
> Var days() As String
> days() = Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
> MessageBox("There are " + days.Count.ToString + " days.")
> ```

<div id="arrays.dimensions">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.Dimensions

**Dimensions** As `Integer</api/data_types/integer>`

> Returns the number of dimensions of the array.
>
> The following example shows how to get the number of dimensions of an Integer array:
>
> ``` xojo
> Var ari(0, 0, 0, 0) As Integer
>
> ' This array has 4 dimensions.
> MessageBox("This array has " + ari.Dimensions.ToString + " dimensions.")
> ```

<div id="arrays.firstindex">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.FirstIndex

**FirstIndex** As `Integer</api/data_types/integer>`

> Returns the index of the first element of the array.
>
> The FirstIndex function is used to determine the first element of an array. This is especially useful for writing code that loops through <span class="title-ref">Arrays</span> so that you don't have to be aware of whether an array begins at 0 or 1 (they all begin at 0).
>
> This code loops through an array and replaces each occurrence of X in an array with Y.
>
> ``` xojo
> For i As Integer = names.FirstIndex To names.LastIndex
>   If names(i) = "X" Then
>     names(i) = "Y"
>   End If
> Next
> ```

<div id="arrays.indexof">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.IndexOf

**IndexOf**(item As DataType, `Optional</api/language/optional>` startIndex As `Integer</api/data_types/integer>`) As `Integer</api/data_types/integer>`

> Used to search for a value in an array. Returns the index of the array element that contains the matching value. <span class="title-ref">Arrays</span> are zero-based.
>
> IndexOf is not case-sensitive, but it is encoding-sensitive.
>
> This example uses a `ComboBox</api/user_interface/desktop/desktopcombobox>` that has five items in its pop-up menu that have the names of the workdays of the week. The selected day is in its Text property. This example returns the index of the array element that matches the menu selection.
>
> ``` xojo
> Var days() As String
> days() = Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
> Var dayNumber As Integer
> dayNumber = days.IndexOf(ComboBox1.Text)
> If dayNumber = -1 Then
>   MessageBox("You didn't enter the name of any weekday.")
> Else
>   MessageBox("You entered day number " + dayNumber.ToString)
> End If
> ```

<div id="arrays.lastindex">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.LastIndex

**LastIndex**(`Optional</api/language/optional>` dimension As `Integer</api/data_types/integer>`) As `Integer</api/data_types/integer>`

> Returns the index of the last element in the array. The optional parameter allows you to get the last index of a specific dimension if the array is multi-dimensional.
>
> For multi-dimensional <span class="title-ref">Arrays</span>, LastIndex returns the index of the last element of the dimension you specify, or, if you do not specify a dimension, it returns the value for the first dimension. The first dimension is numbered 1.
>
> This code replaces each occurrence of X in an array with Y.
>
> ``` xojo
> For i As Integer = names.FirstIndex To names.LastIndex
>   If names(i) = "X" Then
>     names(i) = "Y"
>   End If
> Next
> ```
>
> The following code returns -1 because the newly-declared array has no elements:
>
> ``` xojo
> Var i() As Integer
> Var j As Integer
> j = i.LastIndex
> ```
>
> The following code of a 2-dimensional array returns 5 in the variable i and 3 in the variable j (remember that the first dimension is numbered 1).
>
> ``` xojo
> Var i, j As Integer
> Var aNames(5, 3) As String
> i = aNames.LastIndex
> j = aNames.LastIndex(2)
> ```

<div id="arrays.pop">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.Pop

**Pop** As ArrayType

> Removes the last element from an array and returns its value.
>
> The `Add<arrays.add>` and Pop methods can be used together to treat an array as a stack. The `Add<arrays.add>` method pushes a new element onto the array/stack and the Pop method removes the last element from the array/stack and returns its value.
>
> The type of the value returned is the same type as the array.
>
> If *array* has no values then an `OutOfBoundsException</api/exceptions/outofboundsexception>` is raised.
>
> This example pushes "One", "Two", "Three" onto an array used as a stack and then Pops the values off in reverse order:
>
> ``` xojo
> Var stack() As String
>
> stack.Add("One")
> stack.Add("Two")
> stack.Add("Three")
>
> MessageBox(stack.Pop) ' Three
> MessageBox(stack.Pop) ' Two
> MessageBox(stack.Pop) ' One
> ```
>
> This is a directory-crawling routine that performs a depth-first traversal without using recursion:
>
> ``` xojo
> Var itemsToInspect(0) As FolderItem
> Var item As FolderItem
> Var folder As FolderItem
> folder = FolderItem.ShowSelectFolderDialog
> If folder.Exists Then
>   itemsToInspect(0) = folder
>   While itemsToInspect.LastIndex >= 0
>     item = itemsToInspect.Pop
>     If item.IsFolder Then
>       For Each file As FolderItem In item.Children
>         itemsToInspect.Add(file)
>       Next
>     End If
>   Wend
> End If
> ```

<div id="arrays.removeall">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.RemoveAll

**RemoveAll**

> Removes all elements in the array.

<div id="arrays.removeat">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.RemoveAt

**RemoveAt**(index As `Integer</api/data_types/integer>`)

> Removes the specified element from the array.
>
> The RemoveAt method removes the *index* element from the *array*. The remaining elements are shifted down to the removed element so that there are no gaps in the array.
>
> The RemoveAt method works with one-dimensional <span class="title-ref">Arrays</span> only.
>
> This example removes element 1 from the aNames array:
>
> ``` xojo
> Var names() As String = Array("Bob", "Tom", "Jane")
> names.RemoveAt(1)
> ' names() = "Bob", "Jane"
> ```

<div id="arrays.resizeto">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.ResizeTo

**ResizeTo**(newSize As `Integer</api/data_types/integer>`)

**ResizeTo**(index As `Integer</api/data_types/integer>`, newSize As `Integer</api/data_types/integer>`)

> Resizes the array to the specified *newSize*.
>
> The ResizeTo method is used to increase or reduce the number of rows in the array specified. <span class="title-ref">Arrays</span> are zero-based (the first element is zero) so you resize the array using a number that is one less than the number of elements you actually want. The number of parameters passed is the number of dimensions of the array being resized.
>
> When you resize an array to -1, all rows are removed. It is faster to resize an array in this manner than to loop through the array and individually remove each row. You can use the array `AddRow<arrays.add>` or `AddAt<arrays.addat>` methods to add rows or you can resize it again to the exact size you need.
>
> When you ResizeTo an array to increase its size, any existing values in the array are retained.
>
> When you resize an array to decrease its size, existing values are retained if they are still within the new array bounds.
>
> This example reduces the aNames array to 11 elements.
>
> ``` xojo
> aNames.ResizeTo(10)
> ```
>
> This example adds 10 elements to the aNames array
>
> ``` xojo
> aNames.ResizeTo(aNames.LastIndex + 10)
> ```
>
> This example reduces the aPeople array to 11 elements for the first dimension and 6 elements for the second dimension
>
> ``` xojo
> aPeople.ResizeTo(10, 5)
> ```
>
> When you resize an array with no bounds, its elements are removed. This is a fast way to clear out an array:
>
> ``` xojo
> aNames.ResizeTo(-1)
> ```

<div id="arrays.shuffle">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.Shuffle

**Shuffle**

> Shuffles (rearranges randomly) the elements of an array.
>
> Shuffle works on <span class="title-ref">Arrays</span> of any data type and any number of dimensions. It is based on a random number. An element of the original array has a roughly equal chance of appearing in any cell of the array after the shuffle, regardless of the size and number of dimensions of the array.
>
> A [Fisher-Yates](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle) shuffle is used. There is no ability to control the seed.
>
> Shuffle a one-dimensional array:
>
> ``` xojo
> Var values() As Integer = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
> values.Shuffle
>
> Var result As String
> For i As Integer = 0 To values.LastIndex
>   result = result + i.ToString
> Next
> ```
>
> Shuffle a two-dimensional array:
>
> ``` xojo
> Var myArray(5, 5) As String
> For i As Integer = 0 To 5
>   For j As Integer = 0 To 5
>     myArray(i, j) = i.ToString + j.ToString
>   Next
> Next
> myArray.Shuffle
> ```

<div id="arrays.sort">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.Sort

**Sort**

> Sorts the elements of a one-dimensional array in ascending order.
>
> You can only use Sort with one-dimensional arrays. This signature works with the following data types: Single, Double, Integer (and all related Integer types) and String. String sorting is case-insensitive.
>
> <div class="note">
>
> <div class="title">
>
> Note
>
> </div>
>
> When sorting strings, because a character with a diacritical (é for example) is not a difference in case, they are not grouped with the same character minus the diacritical.
>
> </div>
>
> If you need to sort some other data type, use the other Sort signature (below) that takes a delegate.
>
> <div class="tip">
>
> <div class="title">
>
> Tip
>
> </div>
>
> You can get the equivalent of a descending sort by sorting the array and then accessing it in reverse order with a `For Loop</api/language/loops/for...next>` using the DownTo keyword.
>
> </div>
>
> This example sorts the aNames array.
>
> ``` xojo
> Var names() As String = Array("Jim", "Bob", "Jane")
> names.Sort
>
> ' names = "Bob", "Jane", "Jim"
>
> ' For a descending sort, access the array in reverse order
> Var reverseNames() As String
> For i As Integer = names.LastIndex DownTo 0
>   reverseNames.Add(names(i))
> Next
>
> ' reverseNames = "Jim", "Jane", "Bob"
> ```

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

<div class="rst-class">

forsearch

</div>

Arrays.Sort

**Sort**(`AddressOf</api/language/addressof>` methodName)

> Sorts the elements of a one-dimensional array in ascending order using the method whose address is passed.
>
> Sort an array of DateTimes using a Delegate:
>
> ``` xojo
> Function DateCompare(value1 As DateTime, value2 As DateTime) As Integer
>     ' This assumes the array is populated with non-Nil dates
>     If value1.SecondsFrom1970 > value2.SecondsFrom1970 Then Return 1
>     If value1.SecondsFrom1970 < value2.SecondsFrom1970 Then Return -1
>     Return 0
> End Function
>
> Var myArray() As DateTime
> myArray.Add(DateTime.Now)
> myArray.Add(New DateTime(2015, 8, 21))
> myArray.Add(New DateTime(2014, 4, 21))
> myArray.Add(New DateTime(2016, 11, 21))
>
> myArray.Sort(AddressOf DateCompare)
> ' The array is now sorted
> ```

<div id="arrays.sortwith">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Arrays.SortWith

**SortWith**(array1 As `Array</api/language/array>`, \[arrayN As `Array</api/language/array>`\])

> Sorts one or more additional <span class="title-ref">Arrays</span> in the same order as the base array. The sort is in ascending order.
>
> <div class="tip">
>
> <div class="title">
>
> Tip
>
> </div>
>
> You can get the equivalent of a descending sort by sorting the array and then accessing it in reverse order with a `For Loop</api/language/loops/for...next>` using the DownTo keyword.
>
> </div>
>
> The base array used with the SortWith method works with `Integer</api/data_types/integer>` (and related types), `String</api/data_types/string>`, `String</api/data_types/string>`, `Single</api/data_types/single>`, and `Double</api/data_types/double>` <span class="title-ref">Arrays</span> only. It accepts only one-dimensional <span class="title-ref">Arrays</span> and it should have unique values. Results are undefined when the elements of the base array are not unique, i.e., elements of the base array are all of the same integer value.
>
> SortWith is ideal for sorting all the columns of a data table by one of its columns. For example, if you have a set of three <span class="title-ref">Arrays</span> that store Names, Addresses, and Phone numbers of a group of people, you can sort the data table by Name by specifying the Names array as the base array and pass the Address and Phone number <span class="title-ref">Arrays</span> as the parameters.
>
> Sort two related \`Arrays\`:
>
> ``` xojo
> Var names() As String = Array("Mozart", "Bing", "Jackson", "Flintstone")
> Var zips() As String = Array("04101", "04240", "04123", "04092")
>
> names.SortWith(zips)
>
> ' names() = "Bing", "Flintstone", "Jackson", "Mozart"
> ' zips = "04240", "04092", "04123", "04101"
> ```
>
> Sort an array of objects using one of its values:
>
> ``` xojo
> ' Person is a class containing a LastName property
> ' Assume there is an array called People() As Person that contains
> ' a collection of Person objects
> ' Save the last names into their own array
> Var lastNames() As String
> For i As Integer = 0 To People.LastIndex
>   lastNames.Add(People(i).LastName)
> Next
>
> ' Now sort the last names and provide the people array
> lastNames.SortWith(People)
>
> ' The People array is now sorted to match the last names
> ```

## Notes

Arrays can have a maximum index value of 2,147,483,646 for both 32-bit and 64-bit apps. In addition, although the methods Count, FirstIndex, IndexOf and LastIndex all indicates they return an Integer, they technically return an `Int32</api/data_types/additional_types/int32>` (even with 64-bit app). If you are creating `Extension</api/language/extends>` methods on `Integer</api/data_types/integer>` you should keep this in mind as you may also want to create `Int32</api/data_types/additional_types/int32>` extension methods as well.

Arrays are treated as objects so be aware that assigning an array to another variable or passing an array as a parameter does not make a copy of the array. Instead you get a new variable that points to the original array so any changes you make to the "2nd" array also affects the first array. If you need an actual copy of the array you will have to manually copy its values using a loop.

Arrays are often created by specifying the size of the array when you create it. Because <span class="title-ref">Arrays</span> all start at position 0, an array has one more element than the number you use as the size. For example, this creates an array with 5 elements, which you can then access using the index:

``` xojo
Var aNames(4) As String
aNames(0) = "Bob"
aNames(1) = "Bill"
aNames(2) = "Ben"
aNames(3) = "Brad"
aNames(4) = "Bart"
```

One way to avoid having to remember that <span class="title-ref">Arrays</span> start at zero is to use the `FirstIndex<arrays.firstindex>` and `LastIndex<arrays.lastindex>` methods.

Constants can be used when declaring the size of an array:

``` xojo
Const kBound As Integer = 4
Var aNames(kBound)
```

You can also create empty <span class="title-ref">Arrays</span> that do not specify a size. An empty array has a size of -1. At runtime, your code can add elements to it or you can choose to make it a specific size by using `ResizeTo<arrays.resizeto>`. These are the two ways to create an empty array:

``` xojo
Var aFirstNames() As String
Var aLastNames(-1) As String
```

If you try to access an element of an array that does not exist, you will get an `OutOfBoundsException</api/exceptions/outofboundsexception>`. Here are some examples that would raise the exception:

``` xojo
aNames(5) = "Tom" ' this exceeds the upper bound of aNames
aFirstName(1) = "Bill" ' aFirstName is still empty
```

Use the methods `Add<arrays.add>` and `AddAt<arrays.addat>` to add additional elements to <span class="title-ref">Arrays</span>. These methods are the only ways to add elements to empty <span class="title-ref">Arrays</span>, but they can also be used to extend the size of any single-dimension array.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### Iterating through an array

If you need to access each element of an array but don't need to know the index of that element, you can use an iterator:

``` xojo
Var people() As String = Array("John", "Sally", "Fred", "Nancy")
For Each name As String In People
  MessageBox(name)
Next
```

You can also cycle through an array by index:

``` xojo
Var people() As String = Array("John", "Sally", "Fred", "Nancy")
For index As Integer = 0 To people.LastIndex
  Var name As String = people(index)
  MessageBox(name)
Next
```

There is no real advantage to caching the array's last index in a variable to use in a loop. Over millions of iterations, it will only save a few milliseconds.

If the array is stored in a variant, you must cast the variant as an array in order to access it.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### Multi-dimensional arrays

A multi-dimensional array has elements in 2 or more dimensions. A table would be an example of a 2-dimensional array because it has columns and rows.

Most of the array methods are not supported for multi-dimensional <span class="title-ref">Arrays</span>.

You declare multi-dimensional <span class="title-ref">Arrays</span> by specifying the size for each dimension:

``` xojo
' A 5x5 table
Var table(4, 4) As Integer
table(1, 3) = 42
```

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### Remove all elements

The fast way to remove all elements from an array is to use `RemoveAll<arrays.removeall>`:

``` xojo
Var myArray() As Integer
For i As Integer = 1 To 1000
  myArray.Add(i)
Next
myArray.RemoveAll
' myArray is now empty
```

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### Objects in arrays

Arrays of objects work like other <span class="title-ref">Arrays</span> except you'll have to deal with possible `Nil</api/language/nil>` values just as you would with objects that are not in an array.

If the array index is valid and its value is `Nil</api/language/nil>` and you try to use the value, then you get a `NilObjectException</api/exceptions/nilobjectexception>`, just as you would if you try to use any non-array value that is `Nil</api/language/nil>`.

If an array index is not valid then that's an `OutOfBoundsException</api/exceptions/outofboundsexception>` and is not related to anything being `Nil</api/language/nil>`.

## Compatibility

|                       |     |
|-----------------------|-----|
| **Project Types**     | All |
| **Operating Systems** | All |

<div class="seealso">

`Array</api/language/array>`, `Var</api/language/var>`, `For Each...Next</api/language/loops/for_each...next>`, `ParamArray</api/language/paramarray>` commands; `Dictionary</api/language/dictionary>` class; `Collections of Data</getting_started/using_the_xojo_language/collections_of_data>` topic

</div>
