PHP Memcached Decrement Operation (Detailed Guide w/ Code Examples)

Use Case(s)

Typically, the decr operation in Memcached is used when you want to decrease a numeric item's value. This can be particularly useful in scenarios such as rate limiting or managing counters where you need to reduce a count by a certain amount.

Code Examples

Here's an example of using decr with PHP and Memcached:

<?php // Create a memcached instance $mem = new Memcached(); $mem->addServer("localhost", 11211); // Set a key-value pair $mem->set('counter', 20); // Decrement the 'counter' value by 5 $mem->decrement('counter', 5); // Get the 'counter' value echo $mem->get('counter'); ?>

In this script, we first create an instance of Memcached and add a server. We then set a 'counter' with initial value of 20. The decrement command decreases the 'counter' value by 5, and finally we retrieve and print the updated value of 'counter', which will output '15'.

Best Practices

  • Always check whether the operation was successful or not. Memcached functions return FALSE if something went wrong.
  • Ensure that keys you plan to decrement are already initialized and contain numeric values, as decr cannot be applied on non-numeric values.

Common Mistakes

  • Attempting to decrement a non-existent key: If you try to decrement a key that doesn't exist, Memcached won't create it for you. You must ensure the key exists before you attempt to decrement it.
  • Attempting to decrement a non-numeric value: If you attempt to decrement a value that isn't numeric, it will result in an error.


Q: What happens if I try to decrement the value below 0?
A: If a decrement operation would result in a negative value, Memcached will return and store the value as 0.

Q: Can I use decr on a string value?
A: No, decr can only be used on numeric values. If used on string or other non-numeric types, it will return an error.

Was this content helpful?

Start building today

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