predisHow can I list keys in Redis using PHP?
The easiest way to list keys in Redis using PHP is by using the SCAN command.
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$it = NULL;
$keys = array();
while($arr_keys = $redis->scan($it)) {
foreach($arr_keys as $str_key) {
$keys[] = $str_key;
}
}
print_r($keys);
Output example
Array
(
[0] => key1
[1] => key2
[2] => key3
[3] => key4
[4] => key5
)
The code above will connect to the local Redis server, then loop through the keys using the scan command. The $it variable is used to keep track of the iteration. The $arr_keys variable will hold the keys returned from the scan command and then they are added to the $keys array. Finally, the $keys array is printed using print_r.
Parts of the code:
$redis = new Redis();: Creates a new Redis instance.$redis->connect('127.0.0.1', 6379);: Connects to the local Redis server.$it = NULL;: Initializes the$itvariable.$keys = array();: Initializes the$keysarray.while($arr_keys = $redis->scan($it)) {: Loops through the keys using thescancommand.foreach($arr_keys as $str_key) {: Loops through the array of keys returned fromscan.$keys[] = $str_key;: Adds each key to the$keysarray.print_r($keys);: Prints the$keysarray.
Helpful links
More of Predis
- How can I use PHP and Redis to retrieve data from a sorted set using ZRANGEBYSCORE?
- How can I troubleshoot a "PHP Redis went away" error?
- How do I install and configure a PHP Redis DLL on a Windows machine?
- How can I install and use Redis on a MacOS system with PHP?
- How can I install and configure PHP and Redis on a Windows system?
- How do I use PHP to subscribe to Redis?
- How do I set an expiration time for a Redis key using PHP?
- How do I use the PHP Redis rawcommand?
- How do I use HSCAN to retrieve data from Redis with PHP?
- How do I save an object in Redis using PHP?
See more codes...