0
0
BlockchainConceptBeginner · 3 min read

What is Array in Solidity: Explanation and Example

In Solidity, an 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.

solidity
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 push to add elements to dynamic arrays.

Key Takeaways

Arrays in Solidity hold multiple values of the same type in a specific order.
Use dynamic arrays when the number of elements can change during contract execution.
Access array elements using zero-based indexes to read or update values.
Arrays help manage collections like user lists, scores, or items in smart contracts.
Fixed-size arrays are useful when the number of elements is constant and known.