Memcached Append in PHP (Detailed Guide w/ Code Examples)

Use Case(s)

The append operation in Memcached is useful when you want to add data to an existing value without reading it first. This method can be used for a variety of applications, such as maintaining log files, building complex strings, or accumulating counters.

Code Examples

<?php $mem = new Memcached(); $mem->addServer("localhost", 11211); // Setting a key/value $mem->set("my_key", "Hello"); // Appending data to the existing value $mem->append("my_key", " World!"); // Getting value echo $mem->get("my_key"); // Outputs: Hello World! ?>

In this example, we first create a memcached instance and connect to our local Memcached server. We then set a value ("Hello") for our key ("my_key"). After that, we append " World!" to our existing value. When we get the key "my_key", it outputs "Hello World!".

Best Practices

  • Always check if the key exists before appending to it. If the key does not exist, the append operation will fail.
  • Be mindful of the size of the data you are appending. Memcached has a default limit of 1MB per key-value pair.

Common Mistakes

  • Attempting to append a non-string value onto a string. Memcached's append operation only works with strings.
  • Assuming that append operation will automatically create a key if it doesn't exist. It will actually fail if the key hasn't been previously set.


Q: Can I use append operation for keys storing non-string values?

A: No, the append operation is only valid for string values.

Q: What happens if I try to append data to a non-existing key?

A: The append operation will fail. Memcached doesn't create a new key-value pair if the key doesn't exist.

Was this content helpful?

Start building today

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