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

Use Case(s)

The HEXISTS command in Redis is used to check if a certain hash field exists or not. This is particularly useful when you need to ensure that a given key-value pair is present in the hash before performing operations like HGET or HDEL.

Code Examples

Here's an example of using HEXISTS in PHP using the Predis client:

require 'predis/autoload.php'; $client = new Predis\Client(); // Setting hash fields $client->hset('user:1', ['name' => 'John Doe', 'email' => '']); // Checking if a field exists if ($client->hexists('user:1', 'email')) { echo 'Email field exists.'; } else { echo 'Email field does not exist.'; }

In this code, we first set some fields for the hash user:1, and then use HEXISTS to check if the 'email' field exists in this hash. The HEXISTS method will return true if the field exists and false if it doesn't.

Best Practices

  • Always check if a field exists in your hash before attempting to retrieve or delete it. This will prevent unnecessary errors.
  • Keep the names of your hash fields consistent across your codebase to avoid confusion and potential bugs.

Common Mistakes

  • Using a non-existent hash or field with HEXISTS. Always make sure that the hash and the field you're checking exist in your Redis database.
  • Not handling the boolean result of HEXISTS correctly. Remember that it returns true if the field exists and false if it doesn't.


1. What happens if I use HEXISTS on a non-existent hash? It will return false, just like it would for a non-existent field in an existing hash.

2. Can I use HEXISTS to check the existence of multiple fields at once? No, HEXISTS can only be used to check one field at a time. However, you could write a loop in your PHP code to check multiple fields.

Was this content helpful?

Start building today

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