Stores a string value at a key, optionally with atomic NX/XX and EX/PX options.
The objective is to understand the behavior and operational limits, not only the method name.
What It Does
Stores a string value at a key, optionally with atomic NX/XX and EX/PX options.
Syntax and Return Value
Redis::set(...)
The return value and exceptional cases depend on the call described here: Plain SET removes an existing TTL unless options preserve it; avoid get-then-set for locks.
Requirements: install and enable the corresponding PHP driver or extension and configure the service before running the examples.
Example 1: Basic Use
Requires the phpredis extension and a running Redis server. Keys use a guide-specific prefix; clean up example keys after experimenting.
<?php
$redis = new Redis();
$redis->connect(getenv('REDIS_HOST') ?: '127.0.0.1', (int) (getenv('REDIS_PORT') ?: 6379), 2.0);
$redis->set('guide:set:1','draft',["ex"=>90,"nx"]);
echo $redis->get('guide:set:1') ?: "already exists";
Example 2: A Second Scenario
Requires the phpredis extension and a running Redis server. Keys use a guide-specific prefix; clean up example keys after experimenting.
<?php
$redis = new Redis();
$redis->connect(getenv('REDIS_HOST') ?: '127.0.0.1', (int) (getenv('REDIS_PORT') ?: 6379), 2.0);
$redis->set('guide:set:2','review',["ex"=>90,"nx"]);
echo $redis->get('guide:set:2') ?: "already exists";
Example 3: Practical Checks
Requires the phpredis extension and a running Redis server. Keys use a guide-specific prefix; clean up example keys after experimenting.
<?php
$redis = new Redis();
$redis->connect(getenv('REDIS_HOST') ?: '127.0.0.1', (int) (getenv('REDIS_PORT') ?: 6379), 2.0);
$redis->set('guide:set:3','published',["ex"=>90,"nx"]);
echo $redis->get('guide:set:3') ?: "already exists";
Important Behavior and Edge Cases
Plain SET removes an existing TTL unless options preserve it; avoid get-then-set for locks.
For production use, also account for error handling, data validation, resource limits and environment-specific driver behavior.
Comparison with Related Approaches
| Approach | Important distinction |
|---|---|
| Redis::set | Stores a string value at a key, optionally with atomic NX/XX and EX/PX options. |
| Related API / pattern | setex stores with expiration in one command. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Assuming the happy path covers edge cases | Plain SET removes an existing TTL unless options preserve it; avoid get-then-set for locks. |
| Using a related API interchangeably | setex stores with expiration in one command. |
Key Takeaways
- Stores a string value at a key, optionally with atomic NX/XX and EX/PX options.
- Plain SET removes an existing TTL unless options preserve it; avoid get-then-set for locks.
- setex stores with expiration in one command.
Choose this API or pattern when its exact semantics match your task, and verify the result against the database driver and runtime used by your application.