solidity check if array contains
To check if an array contains a specific element in Solidity, you can use the contains
function from the EnumerableSet
library. Here's an example:
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
contract ArrayContainsExample {
using EnumerableSet for EnumerableSet.UintSet;
EnumerableSet.UintSet private myArray;
function addElement(uint256 element) public {
myArray.add(element);
}
function checkIfElementExists(uint256 element) public view returns (bool) {
return myArray.contains(element);
}
}
In this example, we import the EnumerableSet
library from the OpenZeppelin Contracts library. We then create an instance of EnumerableSet.UintSet
called myArray
. The addElement
function is used to add elements to myArray
, and the checkIfElementExists
function checks if a given element exists in myArray
using the contains
function.
Please note that you need to have the OpenZeppelin Contracts library installed and imported in your Solidity project for this code to work.