Better Programming

Advice for programmers.

Follow publication

Member-only story

A Quick Guide to Arrays in Solidity

Kristaps Grinbergs
Better Programming
Published in
3 min readMar 2, 2022

--

Photo by JJ Ying on Unsplash.

Arrays in Solidity programming language can hold primitive data types like integers, boolean, and string. An array can be initialized with a fixed or dynamic size. If we compare them to other more advanced programming languages, there are pretty limited functions available to work with arrays. Despite that, we can add, remove, get the size of the array, and more.

Initialize an array

We can create an array in Solidity, either having a dynamic or fixed size of the elements that it can hold.

Using a fixed-size array can reduce gas costs but not always we can predict the size of the elements.

Dynamic size

When creating a dynamic array in Solidity, we need to provide the data type that it can hold. Unfortunately, arrays can’t have multiple data types in one array.

uint256[] array;

Fixed size

Another option is to provide the size of the elements that an array can hold. This can save gas costs, especially when creating smart contracts on the Ethereum blockchain.

uint256[10] array;

Behind the scenes, Solidity fills the array with default values, which for the uint256 is 0 (zero).

We can also provide the values when initializing an array.

uint256[] array = [1,2,3];

Add an element

We can add a new element for the dynamic type of arrays. To do that, we need to use the push method. It adds an element to the end of an array.

Here is an example of adding 100 to the array that holds uint256 values.

array.push(100);

Change an element

When changing an element, we need to provide the index and the new value.

Let’s say we want to change the first element’s value in the array.

array[0] = 101;

Get the size of the array

To get the size of the array then, we should use the length function.

--

--

Kristaps Grinbergs
Kristaps Grinbergs

Written by Kristaps Grinbergs

Blockchain, mobile and fullstack developer. Startup founder. Conference speaker. Mentor. Passionate about building products, sustainability and Web 3.0.

No responses yet

Write a response