Having a difficult time with loops and arrays in Solidity. If i have a simple contract like below (no mapping, just a struct array), is it possible to loop through the array to get a particular EntityStruct? Anyone care to show me what this might look like as far as setting up the loop is concerned?

contract simpleList {
     struct EntityStruct {
        address entityAddress;
        uint entityData;
     EntityStruct[] public entityStructs;

1 Answer 1


You can use a simple for loop. Like this:

function test() public view {
     for (uint i; i < entityStructs.length; i++) {
         address firstAddr = entityStructs[i].entityAddress;

You can manipulate the values inside the loop as you want.

  • Thank you for the response. One question though... does this function have to take address as an argument/input? Where do i input the address I want to look up in the array?
    – Blockpain
    Commented Sep 22, 2021 at 22:04
  • No it doesn't have to. It depends on what you need. If you want to find a specific address from the array, then you probably want to take the address as an argument, and compare it against the addresses inside the loop. Something like if (paramAddr == entityStructs[i].entityAddress) { doSomething } Commented Sep 23, 2021 at 4:38
  • Keep in mind that looping in smart contracts is expensive. If you want to know something about a specific address that has been added through some function then use a mapping so you can perform a lookup in a single operation with O(1) time. You may combine this with an array since mappings can't be iterated eg. with a for loop.
    – HankCa
    Commented Nov 11, 2023 at 23:14

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.