Redis HINCRBYFLOAT in PHP (Detailed Guide w/ Code Examples)

Use Case(s)

The HINCRBYFLOAT command in Redis is used to increment the float value of a hash field by the given amount. This can be useful when you're keeping track of high-precision numeric values in a hash and need to increase them incrementally. Some common use cases include:

  1. Tracking high-precision metrics like system load, temperature readings, etc.
  2. Financial calculations where precision is critical.
  3. Incrementing user or session-specific counters in a web application.

Code Examples

<?php // Connecting to Redis server on localhost $redis = new Redis(); $redis->connect('', 6379); // Using HINCRBYFLOAT to increment a hash field $redis->hSet("hash", "field", 10.5); echo $redis->hIncrByFloat("hash", "field", 1.5); // Outputs: 12.0 ?>

In this example, we first set up a connection to the Redis server. Next, we create a Redis hash named "hash" and add a field called "field" with a float value of 10.5. We then use hIncrByFloat to increment the value of "field" by 1.5, yielding a final result of 12.0 .

Best Practices

  1. Be careful with floating-point precision: Even though Redis allows very high precision numbers, floating-point arithmetic can sometimes lead to precision errors. Make sure your application can handle slight rounding errors.
  2. Handle non-existent keys gracefully: If you try to increment a non-existent key with HINCRBYFLOAT, Redis will treat it as having an initial value of 0.

Common Mistakes

  1. Forgetting that HINCRBYFLOAT works only on string keys: If you try to use HINCRBYFLOAT on a key storing a data type other than a string, Redis will return an error.
  2. Not checking for the existence of the key before incrementing: While Redis will treat a non-existent key as 0 and perform the operation, this may not always be expected in your application's logic.


  1. What happens if I try to increment a non-existent key?
    Redis will treat the non-existent key as having an initial value of 0, and then perform the increment operation.

  2. Can I decrement a value using HINCRBYFLOAT?
    Yes, by providing a negative float value to the HINCRBYFLOAT command, you can effectively decrement the value of a hash field.

Was this content helpful?

Start building today

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