I would like to create an array of uints of arbitrary length without having to iterate in a loop, as this seems like it would be costly for large arrays.

e.g. given a count of 5 and a start index of 8 I would like to construct a memory array of [ 8, 9, 10, 11, 12 ].

The code below is the best I currently have. The function signature is just an example the important bit is how I get a populated array of "values"

function createArray(uint startIndex, uint count) public pure returns (uint[] memory) {
    uint[] memory values = new uint[](count); 
    for (uint i = 0; i < count; i++) {
        values[i] = i + startIndex;
    //... do things with this array
    return values;

Can this be achieved in a more efficient manner?

EDIT: For additional context, I would like to batch-mint nfts on an ERC1155 contract. I don't want to have to specify the ids, just say how many I want minting (hence the count) and the contract will keep an internal value indicating the id of the last minted NFT (hence the start index).

1 Answer 1


Try to define all elements in an array in memory, then push all elements once:

uint [] public myArray;
function createArray (uint startIndex, uint count) public returns(uint[] memory){
   uint[] memory newArray;

   for (uint i = 0 ; i < count+1; i++) {
      newArray[i] = startIndex + i;
   myArray = newArray;
   return myArray;
  • newArray is uninitialized, so the contract will revert.
    – Ismael
    Mar 20, 2023 at 6:30
  • OMG thats my bad... i wrote unit instead of uint and i and also i needs an uint before.I'll edit it. try again
    – Alireza
    Mar 20, 2023 at 12:25
  • It still using newArray without allocating the memory, and the for condition should be i < count.
    – Ismael
    Mar 20, 2023 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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