Using Memcached Increment Function in PHP (Detailed Guide w/ Code Examples)

Use Case(s)

The Memcached::incr() function in PHP is used to increment a numeric item's value. Common use cases include:

  1. Rate limiting: you can set up keys for each user and increment it every time they make a request.
  2. Counters: tracking the number of page views, downloads, or any other metric where an increment is needed.

Code Examples

Here is an example of using incr() function:

<?php $mem = new Memcached(); $mem->addServer("localhost", 11211); $key = 'counter'; $mem->set($key, 0); // initial value $new_val = $mem->increment($key); echo $new_val; // prints '1' ?>

In this code, we first create a connection to the Memcached server. We then define a key named 'counter' and set its initial value to 0. The incr() function is then used to increment the value of the key. The new value is printed out to the console.

Another example shows how to handle when the key does not exist:

<?php $mem = new Memcached(); $mem->addServer("localhost", 11211); $key = 'non_existent_key'; $new_val = $mem->increment($key); if ($new_val === FALSE) { echo "The key does not exist."; } else { echo $new_val; } ?>

If the key does not exist, the incr() function will return FALSE.

Best Practices

  1. Always check the return value of incr() function. It returns the incremented value on success or FALSE on failure.
  2. Use meaningful keys that represent the data you're storing.

Common Mistakes

  1. Trying to increment non-numeric values. Make sure the value you are trying to increment is numeric.
  2. Not checking if the key exists before calling incr() function, this can lead to unexpected behavior if not handled properly.


Q: Can I decrement a value using Memcached in PHP? A: Yes, you can use the decr() function to decrement a numeric item's value.

Q: What happens if I try to increment a key that does not exist? A: If you try to increment a key that does not exist, the incr() function will return FALSE.

Was this content helpful?

Start building today

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