Returns time-to-live in seconds or sentinel values for missing/nonexpiring keys.
The objective is to understand the behavior and operational limits, not only the method name.
What It Does
Returns time-to-live in seconds or sentinel values for missing/nonexpiring keys.
Syntax and Return Value
Redis::ttl(...)
The return value and exceptional cases depend on the call described here: -1 means the key exists without expiry; -2 means the key does not exist.
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->setex('guide:ttl:1',120,'draft');
echo $redis->ttl('guide:ttl:1');
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->setex('guide:ttl:2',120,'review');
echo $redis->ttl('guide:ttl:2');
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->setex('guide:ttl:3',120,'published');
echo $redis->ttl('guide:ttl:3');
Important Behavior and Edge Cases
-1 means the key exists without expiry; -2 means the key does not exist.
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::ttl | Returns time-to-live in seconds or sentinel values for missing/nonexpiring keys. |
| Related API / pattern | expire assigns TTL; pTTL reports milliseconds. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Assuming the happy path covers edge cases | -1 means the key exists without expiry; -2 means the key does not exist. |
| Using a related API interchangeably | expire assigns TTL; pTTL reports milliseconds. |
Key Takeaways
- Returns time-to-live in seconds or sentinel values for missing/nonexpiring keys.
- -1 means the key exists without expiry; -2 means the key does not exist.
- expire assigns TTL; pTTL reports milliseconds.
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.