Check if a key exists in Memcache

Matic picture Matic · Jun 22, 2010 · Viewed 18.2k times · Source

How do I check in PHP if a value is stored in Memcache without fetching it? I don't like fetching it because the values I have set are all 1MB in size and after I fetch it, I have no use for it, so I'm wasting resources. I'm using this in a script that checks if certain keys are cached in memcache and if not, it reads them from a slow data source and sets them in memcache.

Edit: What if I use Memcached::append to append NULL to the key I'm checking? Returns TRUE on success or FALSE on failure. The Memcached::getResultCode will return Memcached::RES_NOTSTORED if the key does not exist. This way I check whether the key exists and it should put the key on top of the LRU list right?

Thank you.

Answer

user487772 picture user487772 · Jan 1, 2015

I wonder why Memcached has no special method for it. Here is what I came down to after some considerations:

function has($key)
{
    $m->get($key)

    return \Memcached::RES_NOTFOUND !== $m->getResultCode();
}