The array is a data structure to store multiple variable values under a single name.
For example, If we want to store three numbers,
Declare and assign three variable values with the same int type, Example is number1=0,number2=1, and number3=1.
With arrays, we can represent a single variable to store all values. Each value of an array can be accessed using an index that starts from zero to array.length-1.
Array
is one of the reference types defined in a solidity programming language.
Arrays are of two types
Fixed array
: Array created with a fixed size of elements during declaration.Dynamic array
: Array created with dynamic size and no fixed size size
How to declare an array in a solidity?
Variables declared of a string with the below syntax.
type[size] arrayvariablename =initialization;
type
is a data type of an array of data i.e value or reference types.
size
is several elements to store for arrays. size is optional for the dynamic array.
arrayvariablename
is a valid identifier and valid names are alphanumeric which starting must be a letter. Reserved words not used with value.
initialization
: initialize the data for an array
Fixed Array in Solidity
A string array is created with a fixed size of 5 elements.
string[5] stringArray;
Dynamic Array in Solidity
dynamic array is dynamically grown array size during the execution of code. No fixed size.
string[] numbers;
How to initialize a static string array in solidity?
Arrays can be declared as global in the contract or inside the function.
Array variable created by assigning the values using square brackets
pragma solidity ^0.8.4;
contract StaticArrayTest {
string[3] numbers = ["one", "two", "three"];
function getNumbers() external {
string[3] memory mynumbers = ["one", "two", "three"];
}
}
How to return arrays from functions
By default, It does not support returning an array from a function.
ABIEncoderV2
experimental needs to be used in a contract.
pragma solidity ^0.5.2;
pragma experimental ABIEncoderV2;
contract Test {
string[] array;
function push(string calldata _text) external {
array.push(_text);
}
function get() external view returns(string[] memory) {
return array;
}
}
Operators and methods
length
: length of an array
push
: adds an element to a dynamic array. It adds an element to the last position of an array.
pop
: removes an element from the dynamic array. It deletes an element from the last element of an array.