What is Array in Solidity: Explanation and Example
array is a collection of elements of the same type stored in a specific order. Arrays can be fixed-size or dynamic, allowing you to store multiple values like a list or a row of boxes.How It Works
An array in Solidity is like a row of boxes where each box holds a value of the same type, such as numbers or addresses. You can think of it as a shelf with slots, each slot labeled by a number starting from zero. This number is called the index, and it helps you find or change the value inside that slot.
There are two main types of arrays: fixed-size and dynamic. Fixed-size arrays have a set number of slots that cannot change, like a box with exactly five compartments. Dynamic arrays can grow or shrink, like a flexible shelf where you can add or remove compartments as needed.
Arrays help organize data efficiently, making it easy to store and access multiple related values in your smart contract.
Example
This example shows how to declare a dynamic array of numbers, add values to it, and read a value by its index.
pragma solidity ^0.8.0; contract ArrayExample { uint[] public numbers; // dynamic array of unsigned integers // Add a number to the array function addNumber(uint _number) public { numbers.push(_number); } // Get number at a specific index function getNumber(uint _index) public view returns (uint) { require(_index < numbers.length, "Index out of range"); return numbers[_index]; } // Get the total count of numbers function getCount() public view returns (uint) { return numbers.length; } }
When to Use
Use arrays in Solidity when you need to store multiple values of the same type together. For example, you might keep a list of user addresses who joined a game, store scores, or track items in a marketplace.
Arrays are useful when order matters or when you want to access elements by their position. Dynamic arrays are great when the number of items can change over time, while fixed-size arrays work well for a known, constant number of elements.
Key Points
- Arrays store multiple values of the same type in order.
- Fixed-size arrays have a set length; dynamic arrays can grow or shrink.
- Array elements are accessed by zero-based index.
- Arrays help organize related data efficiently in smart contracts.
- Use
pushto add elements to dynamic arrays.