[Solidity] How to get the array length?

This section explains how to get the length (number of elements) of an array in Solidity.

Syntax

To get the length of an array in Solidity, use the length method.

array.length

Sample Code

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract Test {
    uint[] public array = [1, 2, 3];

    function getLength() public view returns(uint) {
        // Get the length (number of elements) of the array
        return array.length;
    }
}

Just like any other programming language! Since the operations are inseparable from arrays, make sure to keep them in mind.

タイトルとURLをコピーしました