Solidity Arrays
An array is a list of values of the same type stored in order. Each item sits at a numbered position called an index.
A fixed-size array made with starting values
uint256[3] holds exactly three numbers. The values in brackets become its starting items.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract ScoreList {
uint256[3] public scores = [10, 20, 30];
}
A dynamic array has no fixed size
Empty brackets make a dynamic array. Its size is not fixed in the declaration.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract PriceList {
uint256[] public prices = [100, 200];
}
Reading one item by its index
Give an index in brackets to read one item. Index 1 reads the second item.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract ReadingList {
uint256[] public pages = [12, 20, 8];
function getSecond() public view returns (uint256) {
return pages[1];
}
}
The length of a dynamic array
The length says how many items an array holds. This array holds four items.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract TeamScores {
uint256[] public scores = [8, 16, 24, 32];
function count() public view returns (uint256) {
return scores.length;
}
}
Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract ChapterPages {
uint256[] public pages = [12, 20, 8];
function getFirst() public view returns (uint256) {
return pages[0];
}
function count() public view returns (uint256) {
return pages.length;
}
}
Key points
- Array: a list of values of one type, stored in order.
- Index: the position of an item in an array, starting at 0 for the first item.
- Fixed-size array: uint256[3] holds exactly three numbers.
- Dynamic array: uint256[] has no size fixed in its declaration.
- Reading: scores[1] reads the item at index 1, which is the second item.
- Length: scores.length gives how many items the array holds.
In this example, pages is a dynamic array with three starting values. The getFirst function reads the item at index 0. The count function returns pages.length. Together they show both one item and the size of the whole list.
Note
reading past the last index reverts, because that item does not exist.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
A dynamic array holds four items. What does its length return?