DEV Community

Jeremy Ikwuje for Monierate Engineering Blog

Posted on

How to declare an array in Solidity

You can declare an array in Solidity.

type[length] name = [ ... ];
Enter fullscreen mode Exit fullscreen mode

Arrays in Solidity are fixed collections of elements with the same data type values. Each element has an index(position) within the array. An array is useful for holding fixed or unknown collections of values without having to create a different variable for each value.

Let's say you have vote counts from five polling units. Instead of creating five variables to hold each of these votes count, you create a single array to hold them.

uint[5] votes = [10, 20, 8, 88, 14];
Enter fullscreen mode Exit fullscreen mode

An array starts with the type, length, identifier, and values.

Type is the data type of the array. In the above example, we specify this array should contain only unsigned integers. Solidity support multiple types e.g string.

Length of the array specifies the total values that the array can hold. Our example we set the array to hold only five values. If your array may contain unknown or infinite values, then you can just leave the length empty uint[].

Identifier is the name of the array. Just give it any name that makes sense.

Values are the values in the array.

Hope that helps!

Recommended: How to get the length of an array in Solidity

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay