Exploring Redis Sets

Exploring Redis Sets

Let's dive into how we can work with Redis sets using PHP. Redis, as a versatile key-value store, supports various data structures, including sets, which are collections of unique, unordered elements. In this lesson, we'll look at how to add and retrieve items from sets with PHP.

First things first, let's connect to your Redis server and add some items to a set:

PHP
<?php

require 'vendor/autoload.php';

use Predis\Client;

$client = new Client();

try {
    // Adding items to a set
    $client->sadd('countries', 'USA', 'Canada', 'UK', 'USA');

    // Retrieve all members of the set
    $countries = $client->smembers('countries');
    echo "Countries in the set: " . implode(", ", $countries) . "\n"; // Output: Countries in the set: USA, Canada, UK
} catch (Exception $e) {
    echo "Could not perform the requested operation: ", $e->getMessage(), "\n";
}

?>

Breaking Down the Code

  • We use the Predis library, a PHP client library for Redis.
  • We establish a connection to the Redis server via the Client object.
  • With the sadd command, we add items to a set called countries. The set nature of Redis automatically ensures that no duplicate entries exist.
  • Using the smembers command, we retrieve all members and print them. Despite adding "USA" twice, duplicates are not stored.

Now, let's look into how to find out the number of items in a set and remove a certain item.

PHP
<?php

require 'vendor/autoload.php';

use Predis\Client;

$client = new Client();

try {
    // Get the number of items in the set
    $numCountries = $client->scard('countries');
    echo "Number of countries in the set: $numCountries\n"; // Output: Number of countries in the set: 3

    // Remove an item from the set
    $client->srem('countries', 'UK');

    // Verify removal
    $countries = $client->smembers('countries');
    echo "Countries in the set after removal: " . implode(", ", $countries) . "\n"; // Output: Countries in the set after removal: USA, Canada
} catch (Exception $e) {
    echo "Could not perform the requested operation: ", $e->getMessage(), "\n";
}

?>

Code Explanation

  • We determine the number of items in the set using the scard command, which tells us how many unique items are stored.
  • We then use the srem command to remove the specified item from the set — in this case, "UK".
  • After removal, we can confirm the operation by re-checking the set's current items.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal