When you want a collection of something, you can use an array. There are two types of arrays in Solidity: fixed arrays and dynamic arrays:
// Array with a fixed length of 2 elements:uint[2] fixedArray;
// another fixed Array, can contain 5 strings:string[5] stringArray;
// a dynamic Array - has no fixed size, can keep growing:uint[] dynamicArray;
You can also create an array of structs. Using the previous chapter's Person struct:
erson[] people; // dynamic Array, we can keep adding to it
Remember that state variables are stored permanently in the blockchain? So creating a dynamic array of structs like this can be useful for storing structured data in your contract, kind of like a database.
You can declare an array as public, and Solidity will automatically create a getter method for it. The syntax looks like:
Person[] public people;
Other contracts would then be able to read from, but not write to, this array. So this is a useful pattern for storing public data in your contract.
Arrays can have a compile-time fixed size, or they can have a dynamic size.
The type of an array of fixed size k and element type T is written as T[k], and an array of dynamic size as T[].
For example, an array of 5 dynamic arrays of uint is written as uint[][5]. The notation is reversed compared to some other languages. In Solidity, X[3] is always an array containing three elements of type X, even if X is itself an array. This is not the case in other languages such as C.
Indices are zero-based, and access is in the opposite direction of the declaration.
For example, if you have a variable uint[][5] memory x, you access the seventh uint in the third dynamic array using x[2][6], and to access the third dynamic array, use x[2]. Again, if you have an array T[5] a for a type T that can also be an array, then a[2] always has type T.
Array elements can be of any type, including mapping or struct. The general restrictions for types apply, in that mappings can only be stored in the storage data location and publicly-visible functions need parameters that are ABI types.
It is possible to mark state variable arrays public and have Solidity create a getter. The numeric index becomes a required parameter for the getter.
Accessing an array past its end causes a failing assertion. Methods .push() and .push(value) can be used to append a new element at the end of the array, where .push() appends a zero-initialized element and returns a reference to it.