PHP Memcached Add (Detailed Guide w/ Code Examples)

Use Case(s)

Memcached::add() method in PHP is commonly used when you need to store a new item in memcached if it does not already exist. This can be useful when you're managing cached content and want to avoid overwriting existing keys.

Code Examples

Here's an example of how to use the Memcached::add() function:

<?php $mem = new Memcached(); $mem->addServer("localhost", 11211); $key = "test_key"; $value = "test_value"; // The 'add' method will return true if the item was successfully stored, false otherwise. if($mem->add($key, $value)) { echo "Item has been added.\n"; } else { echo "Item could not be added, or it already exists.\n"; } ?>

In this example, we first create a new instance of the Memcached client and connect to the server running on localhost. Then we define a key-value pair that we want to add to the cache. The add() method attempts to add this item to the cache, and we check its return value to see if the operation was successful.

Best Practices

  • Always check the return value of the add() function. It gives important information about whether the operation was successful.
  • Be aware that add() will not overwrite existing items. If you need to ensure that the item is stored regardless of whether it already exists, consider using the set() method instead.
  • Handle your keys carefully to avoid collisions. Unique and meaningful key design can help prevent overwriting data accidentally.

Common Mistakes

  • Not handling the return values properly. If add() returns false, it doesn't always mean there was a problem with the server or the operation. It could also mean that an item with the same key already exists.
  • Using add() instead of set(). add() will not overwrite existing values, which can lead to confusion if you're expecting it to update values.


Q: What is the difference between add() and set() in Memcached? A: The add() method will only add an item if it does not already exist in the cache. On the other hand, set() will store the item regardless of whether it already exists, overwriting any existing item with the same key.

Q: What happens if I try to add an item with a key that already exists? A: If you use the add() function and the key already exists, the function will return false, and the existing item in the cache will not be overwritten.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.