I am writing a smart contract to be the backend of a game. Instead of using a mapping, I have decided to use an array to store the addresses of accounts who have paid my contract. (I know it is common practice to use a mapping for this but I find them to be confusing)

address[] paidPlayers;

As players join, their address is added via the following function.

function addPlayer(address player) constant returns (address[]) {
   return paidPlayers;

Periodically, when a round in the game is completed, I want my contract to reset. I thus need a way of emptying my paidPlayers array. How is this done in solidity? Is there anything like the javascript

paidPlayers = [];

I have found methods for deleting a specific element but not the array as a whole.


From Solidity Documentation Tips and Tricks

Use delete on arrays to delete all its elements.

delete paidPlayers;

This is exactly the same as paidPlayers.length = 0

| improve this answer | |
  • Caveat! if the array is too large it will cause a run out of gas error! An alternative is to use mappings of uint256 and a totalNumberOfElements to handle where to save the values. In case of clear/reset you set totalNumberOfElements = 0. For inserts, you should use myArray[totalNumberOfElements] = value – imazzara Jan 3 '19 at 15:06
  • @imazzara You are correct but there's an important difference deleting an array will reset all the data to zero. In a case of mapping you have to explicitely delete each item, if you do not delete it and reuse an index it will still have the previous data. – Ismael Jan 3 '19 at 15:57
  • 1
    Right, but it depends on how you manage the access to them. I mean, you can let users only to get items with something like getItemAtIndex where you check the bounds with the valid totalNumberOfElements instead of making the mapping public. The rule should be: "If you are not confident about the size of the array, you will need to use mappings to prevent a possible DoS." Moreover, it saves gas, cause you are re-using the slots instead of empty all of them. – imazzara Jan 3 '19 at 16:02
  • After deleting an array; how much gas refund will be made? would it be 15.000 or the 15.000 * length_of_the_array ? Please see (ethereum.stackexchange.com/q/69882/4575) for more detail in question. @Ismael – alper Apr 19 '19 at 19:02

You can manually set the array length to 0 with

paidPlayers.length = 0;

This will clear all entries in the array.

| improve this answer | |
  • 2
    Note that from Solidity 0.6 onwards the length member is read-only. Using delete is now the right approach. – hiddentao May 14 at 12:58
  • This answer is no more relevant – Haseeb Saeed Jul 12 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.