I have an array.

string[] private NameIndex;

i want to check if the same name is already exist in the array.If same name is exist it will return false and if not exist anf if name is unique it will add the new name in the array and return true.

NameIndex.push("BOB") - 1;

kindly help

  • What do you want to achieve by subtracting one? – Yuanfei Zhu Feb 27 '17 at 11:57
  • 1st entry will go to index 0 – TAMIM HAIDER Feb 27 '17 at 11:58

Solidity provides no obvious way to do this.

One can contemplate an iterative process to search the list, but the gas cost will increase with the size of the list. This puts an upper bound on the size of the list; either by increasing transaction cost to an unacceptable level, or by exceeding the block gas limit so transactions can't run at all.

There are (at least) two general solutions.

  1. Invert control so the client performs the iterative operation and interrogates contract functions one row at a time. It's possible to expose indexed lists (searchable) with event emitters. That may help, but in any case, performance will suffer with list size.

  2. Use a mapping to facilitate random access in a single step.

Since mappings can't be enumerated and it's not possible to know how many keys have been set or what they are, it may be necessary to devise a system of pointers using both arrays and mappings to produce a "list" of randomly accessible items.

Have a look here for a pattern and better explanation: https://bitbucket.org/rhitchens2/soliditycrud/overview

Hope it helps.

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.