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

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