Arrays in solidity from zero to hero

Mahmoud Mourad Dev
Coinmonks
6 min readSep 26, 2022

--

Arrays

  • groups of value type of the same type [10,20,30,40,50]
    - fixed-size array uint[5] myArray
    -dynamic array uint[ ] myArray
    -one dimensional array
    -multi dimensional array

When use different type in array

Add value to dimensional array

Notice how it’s necessary to manually cast the first elements of the sub-arrays to a common type, because Solidity tries to use the small numbers you have in the array (8, 6, 8 4) as uint8 and the big numbers (1200, 1400, etc) as the next type that can hold them, which would be uint16. Since uint8 and uint16 are not compatible, you need to cast at least the first element of each sub-array to a common element so you let Solidity know what is the type of each of those sub-elements.Solidity compiler is not yet smart enough to handle that. Maybe in the future, it will.

Array Members

  • push () accepts an element and add to the end of array

You can’t push to a fixed size array because it has been fixed already, and memory has already been allocated to it. If you want to push, you need to use dynamic arrays. Dynamic arrays have no fixed size, can contain numbers, and keep growing.

  • Length Arrays have length member that contains that elements
  • pop() items can be removed from the array using pop method which remove the last index and adjust the length
  • pop method in dynamic array only
  • Delete member not delete the index (index to zero)

Access elements in array

  • you need to specify the index between square brackets

access elements in multi dimensional array

Special arrays

solidity special array

bytes array
-variable of bytes and string are special array
-bytes is dynamic array can hold any number of bytes
-bytes4 fixed size array / much cheaper
-bytes is similar to bytes[] but bytes is cheaper
-you can run length and pop operation only
-you can not run push operation

string array

  • dynamic data type that are based on dynamic
    -string not allow length
    -string not allow index access
    -string not have manipulation function but there are third-party string libraries you can also compare two string by their keccak256 hash

String dont have length property ,it should be converted in to bytes

String to bytes

Compare two string

The array [1,-1] is invalid because the type of first index is uint8 while the type of second index int8 ,to make it work you can use [int8(1),-1]

Function output array

How to get the largest element in an array — Solidity

Multidimensional arrays in solidity and mapping

Array example contract to check the price in array

Array example check true name -Compare two string

Array example

New to trading? Try crypto trading bots or copy trading

--

--