How to know if a specific value exists in the mapping table or not?
Asked Answered
L

3

8

I have a mapping table whcich stores multiple hashes into that table. What I want to do is that I want the user to add another hash with setinstructors() function and then try to look whether the same hash already exists in the mapping table or not. If the same hash already exists in the table then it should return true esle false. Here's my code:

pragma solidity ^0.4.18;

contract Hash{
bytes32 comphash;

struct hashstruct{
bytes32 fhash;

}
mapping (uint => hashstruct) hashstructs;
uint[] public hashAccts;



function setinstructor(uint _uint,string _fhash) public {
      var a = hashstructs[_uint];
   a.fhash = sha256(_fhash);  
     hashAccts.push(_uint) -1;


}



function getInstructor(uint ins) view public returns (bytes32) {
    return (hashstructs[ins].fhash);
}

   function count() view public returns (uint) {
    return hashAccts.length;
}



function setinstructors(string _comphash) public {
    comphash = sha256(_comphash);

}

function getInstructors() public constant returns (bytes32) {
    return (comphash);
}



}
Losel answered 3/4, 2018 at 19:22 Comment(0)
T
21

There's no such thing as "existence" in a Solidity mapping.

Every key maps to something. If no value has been set yet, then the value is 0.

For your use case, hashstructs[n].fhash > 0 is probably sufficient. If you want to be explicit, add a bool exists to your struct and set it to true when you add something. Then use hashstructs[n].exists to check for existence.

Tammietammuz answered 3/4, 2018 at 19:29 Comment(0)
J
4

If you want to check whether a key exists in the mapping then you can check the byte length. If the length is zero that means the key doesn't exist else key is present in the mapping. A Sample Example is:-


    function checkUser(string memory user_id) public view returns(bool){
        if(bytes(PassHash[user_id]).length>0){
            return true;
        }
        else{
            return false;
        }
    }
Jeth answered 5/4, 2021 at 4:17 Comment(1)
As per v0.8.6: if (abi.encodePacked(PassHash[user_id]).length > 0) { delete balances[addr]; }Upandcoming
E
0

The same as above but with a ternary operator :) It looks a bit more fancy

    function checkUser(string memory user_id) public view returns (bool) {
        return abi.encodePacked(PassHash[user_id]).length > 0 ? true : false;
    }
Earthy answered 13/6, 2022 at 6:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.