Solidity Array Functions

whiteboard crypto logo
Published by:
Whiteboard Crypto
on

There are a few functions (or “members”) you can perform on an array in Solidity. Push, Pop, and Remove are the most popular functions, and here’s a smart contract that uses them:

//SPDX-License-Identifier: MIT
pragma solidity 0.8.13;

contract arrayFunctions{

    uint[] public counting = [0,1,2,3,4];

    function addToArray(uint _numberToAdd) public {
        counting.push(_numberToAdd);
    }

    function reset(uint _index) public{
        delete counting[_index];
    }

    function getLength() public view returns(uint){
        return counting.length;
    }

    function pop() public{
        counting.pop();
    }

    function viewCounting() public view returns(uint[] memory){
        return counting;
    }
}

In the beginning of this contract, you can see that we create a simple array named “counting” that counts from 0 to 4.

The first function named “addToArray” adds an item to the end of the array using the “push” member.

The second function named “reset” uses the delete keyword to reset the value of an unsigned integer in the array. In this case, the default value of an unsigned integer is 0.

The third function named “getLength” returns the length of the array, which would be 5 if you don’t modify the initial “counting” array.

The fourth function named “pop” removes the last item in the array, reducing the length of the array as well.

Finally, the last function is a function we use to view the array in a simple way.

whiteboard crypto logo

WhiteboardCrypto is the #1 online resource for crypto education that explains topics of the cryptocurrency world using analogies, stories, and examples so that anyone can easily understand them. Growing to over 870,000 Youtube subscribers, the content has been shared around the world, played in public conferences and universities, and even in Congress.