I have used solidity to push data into an array. Is there a similar function for pop ?
string[] myArray;
myArray.push("hello")
What is the best solution for this ? How do I delete an element in a dynamic array in solidity ?
I have used solidity to push data into an array. Is there a similar function for pop ?
string[] myArray;
myArray.push("hello")
What is the best solution for this ? How do I delete an element in a dynamic array in solidity ?
Update 2-19-2019: As Joel pointed out below,
pop
has been added to built-in array support. See https://solidity.readthedocs.io/en/v0.5.4/types.html#array-members. Leaving original answer on here in case others are using older versions of Solidity.There is no pop function in Solidity. You have a few options you can consider for maintaining your array.
Delete & Leave Gaps
The simplest solution is to just
delete
the element at a specific index:However, this will NOT shift the elements in your array and will leave an element of "string 0" in your array. To check this element, you would use
if(bytes(myArray[index]).length > 0) ...
Swap & Delete
If you don't care about order in your array, you can swap the element with the last element in your array and then delete:
Delete With Shift
If order in your array is important, you can delete the element then shift all remaining elements to the left.
Note that this will be the most expensive of the options. If your array is very long, you will have high gas usage.
Correlating with @Jedsada's suggestion, here is a version as a library:
Example usage (Important note: You can't use
popElement
and return the value to a client. That method changes state and should only be used within a transaction.):Additional note: Unfortunately,
var
has been deprecated since 0.4.20 and there is no replacement for generics. You have to customize for a specific type.You can try...
Yes there is, as of v0.5.0 (details here):