Hey there, I am pretty sure you have heard of arrays in other programming languages right? This article explains how arrays work in solidity.
Array
An array in solidity is a data structure, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Declaring An Array
There are two ways of declaring arrays in solidity:
Fixed-size Array
Dynamic size Array
Fixed size Array
Fixed-size arrays have a determined size. They cannot be initialized using the **'new' **keyword. They can only be initialized in line. To declare an array of fixed size in Solidity, the programmer specifies the type of the elements and the number of elements required by an array as follows −
type [ arraySize ] arrayName;
In the examples below, T is the element type, and **k ** is the array length/size. If k = 5, the array can hold a maximum of 5 values.
T[k]
// array that can hold 5 unsigned integers maximum
uint[5] myArray;
Dynamic-size Array
Dynamic-size arrays do not have a predetermined size at the time of declaration but their size is determined at runtime. To declare an array of dynamic size in Solidity, the programmer specifies the type of the elements as follows −
type[] arrayName;
// array containing an undefined number of strings,
string[] my_array;
Arrays have built-in functions that allow you to add, update and delete information.
Push: adds an element to the end of the array.
Pop: removes the last element of the array.
Length: gets the length of the array. As an example how many items are in the array.
delete: allows you to delete an item at a specific location in the array
Array Example
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.0;
contract sampleArray {
uint[] public myArray; //this is a dynamic array of type uint
uint[] public myArray2 = [1, 2, 3]; //this is a dynamic array with 1, 2 and 3 as default values
uint[10] public myFixedSizeArray; //this is a fixed size array of type uint
function push(uint i) public {
//this will add i to the end of myArray
// This will increase the array length by 1.
myArray.push(i);
}
function remove(uint index) public {
//this is to delete an item stored at a specific index in the array.
delete myArray[index];
//Once you delete the item the value in the array is set back to 0 for a uint.
}
function getLength() public view returns (uint) {
//this will return the length of myArray
return myArray.length;
}
function pop(uint index) public {
//myArray[myArray.length-1] will return the last element of an array so this complete statement will
//get the last item in the array and put it in the position that we are removing which is myArray[index].
myArray[index] = myArray[myArray.length-1] ;
//then we remove the last element of the array
myArray.pop();
}
}