Lesson 2
Working with Numbers
Working with Numbers

Welcome back to our Redis course! Now that you know how to connect to a Redis server using PHP, it's time to move forward and explore how to work with numbers. This unit builds on our previous lesson, so make sure you're comfortable with establishing a connection to a Redis server.

What You'll Learn

In this lesson, you will learn how to:

  1. Set numeric values.
  2. Retrieve and handle numeric values.

Here's the code snippet that we'll be working with:

php
1<?php 2 3require 'vendor/autoload.php'; 4 5use Predis\Client; 6 7// Connect to Redis 8$client = new Client([ 9 'scheme' => 'tcp', 10 'host' => '127.0.0.1', 11 'port' => 6379, 12]); 13 14// Setting numeric values 15$client->set('count', 5); 16$client->set('completion_rate', 95.5); 17 18// Getting numeric values 19$count = $client->get('count'); 20$completionRate = $client->get('completion_rate'); 21 22echo sprintf("Course count: %d, Completion rate: %.2f\n", $count, $completionRate); 23 24?>
Let's Break Down the Code
  • We start by including the autoload.php from Composer to load the predis/predis package.
  • The Predis\Client class is used to establish a connection to the Redis server. We specify the connection parameters, such as scheme, host, and port.
  • The set method in predis is used to store numeric values (count with a value of 5 and completion_rate with a value of 95.5) into the Redis server.
  • The get method is used to retrieve these numeric values. Note that the values retrieved from Redis will be strings, so when displaying or using them as numbers, be sure to cast them appropriately if necessary. PHP will automatically handle the conversion when using them in numeric contexts like sprintf. An example of casting can be seen below:
php
1<?php 2 3$myString = "23"; 4echo gettype($myString)."\n"; // prints "string" 5$myNumber = (int)$myString; // casting a value as an integer 6echo gettype($myNumber)."\n"; // prints "integer" 7 8?> 9
Why It Matters

Working with numbers in Redis is crucial because many real-world applications involve numeric data. From tracking user statistics to monitoring system performance, managing numbers in Redis allows you to perform a variety of useful operations efficiently. By mastering these basic operations, you'll be well-prepared to tackle more complex tasks and optimize your applications.

Ready to dive in? Let's move on to the practice section and get hands-on experience working with numbers in Redis!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.