3

I want to append data to an item in Memcached. But it seems that if the item does not exist, this action will not create an item and the data just would not be stored. *talking php

Danil K
  • 3,777
  • 2
  • 16
  • 7
  • possible duplicate of [Check if a key exists in Memcache](http://stackoverflow.com/questions/3091107/check-if-a-key-exists-in-memcache) – user487772 Jan 01 '15 at 08:41

3 Answers3

7

To check correctly if an item exists in Memcached / PHP you should do:

$item = $m->get($key);
if ($m->getResultCode() == Memcached::RES_SUCCESS) {
    // item exists ($item value)
} else {
    // item does not exist ($item is probably false)
}
axelbrz
  • 783
  • 1
  • 7
  • 16
4

If Memcache::get() returns false, the key doesn't exist (or an error occurred). Unlike APC, Memcache has no other functionality for verifying existence (or non-existence) of a key.

bcosca
  • 17,371
  • 5
  • 40
  • 51
  • 3
    What about if the requested key holds `false` value? – user487772 Dec 31 '14 at 19:57
  • 3
    After doing `$m->get(KEY)` you should use `$m->getResultCode() == Memcached::RES_SUCCESS` to check if `KEY` exists. Here is a list of possible result codes: http://php.net/manual/en/memcached.set.php#114651 – axelbrz May 05 '15 at 00:01
2

Use append.

If the item does not exist, you will get an error telling you that it didn't exist.

Dustin
  • 89,080
  • 21
  • 111
  • 133