Skip to content
Home ยป Answers ยป How to Create String Arrays in Solidity?

How to Create String Arrays in Solidity?

An array is a data structure that is used to store multiple values of variables under a variable. Letโ€™s see how we can create it in Solidity.

What are arrays in Solidity?

Creating arrays in Solidity is like organizing your belongings in a box. You can have different types of boxes – some with a fixed size, and others that can grow bigger as needed.

Fixed-size arrays

In fixed-size arrays, the array’s size is determined during declaration and must be a positive integer. The count of values provided during initialization should be equal to or less than the specified size of the array.

Let’s understand it using an example. Fixed-size arrays are like boxes you buy that can only hold a certain number of items. When you get the box, you have to decide how many things it can hold, and you can’t put more things than what the box can handle. In Solidity, this means you set the size of the array when you create it, and you can only put that many items inside.

Solidity code example

pragma solidity ^0.8.0;

contract FixedSizeArray {
  
  string [4] fixedArray=["Metaschool", "Nodes", "Discord", "Ethereum"];
  
}

In this example, our array has space for 4 strings, and we’ve put in the names “Metaschool,” “Nodes,” “Discord,” and “Ethereum.”

๐Ÿ”ฅ Check this out: Build in Public

Dynamic-size arrays

In dynamic-size arrays, the array’s size is not determined during declaration instead it usually increases during code execution.

Let’s understand it using an example. Dynamic-size arrays are like magical boxes that can stretch to fit more items. You don’t have to decide how big the box is when you get it; it can grow or shrink as you add or remove items. In Solidity, this means you don’t set the size when you create the array; it can change during the program’s execution.

Solidity code example

pragma solidity ^0.8.0;

contract NotFixedSizeArray {
  
  string [] notFixedArray=["Metaschool", "Nodes", "Discord", "Ethereum"];
  
}

In this case, our array can hold as many strings as we want. We’ve put in the same names as before, but we can add more whenever we need.

๐Ÿ”ฅ Check this course out: Build a Petition Filing dApp on the Fuel Network

Conclusion

Solidity offers both types of arrays – fixed-size and dynamic-size. Fixed-size arrays have a predetermined size during declaration, while dynamic-size arrays can increase in size during code execution. Both types can be utilized efficiently depending on the use-case scenario in your smart contract development.

Follow us on โ€“

๐Ÿ”ฎTwitter โ€“ https://twitter.com/0xmetaschool

๐Ÿ”—LinkedIn โ€“ https://www.linkedin.com/company/0xmetaschool/