Sets a key only if it does not already exist.
The objective is to understand the behavior and operational limits, not only the method name.
What It Does
Sets a key only if it does not already exist.
Syntax and Return Value
Redis::setnx(...)
The return value and exceptional cases depend on the call described here: SETNX alone is unsuitable for expiring locks because no TTL is attached atomically.
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);
echo $redis->setnx('guide:setnx:1','draft') ? "new key" : "already present";
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);
echo $redis->setnx('guide:setnx:2','review') ? "new key" : "already present";
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);
echo $redis->setnx('guide:setnx:3','published') ? "new key" : "already present";
Important Behavior and Edge Cases
SETNX alone is unsuitable for expiring locks because no TTL is attached atomically.
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::setnx | Sets a key only if it does not already exist. |
| Related API / pattern | set with NX and EX/PX combines conditional creation and expiry. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Assuming the happy path covers edge cases | SETNX alone is unsuitable for expiring locks because no TTL is attached atomically. |
| Using a related API interchangeably | set with NX and EX/PX combines conditional creation and expiry. |
Key Takeaways
- Sets a key only if it does not already exist.
- SETNX alone is unsuitable for expiring locks because no TTL is attached atomically.
- set with NX and EX/PX combines conditional creation and expiry.
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.