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$it
variable.$keys = array();
: Initializes the$keys
array.while($arr_keys = $redis->scan($it)) {
: Loops through the keys using thescan
command.foreach($arr_keys as $str_key) {
: Loops through the array of keys returned fromscan
.$keys[] = $str_key;
: Adds each key to the$keys
array.print_r($keys);
: Prints the$keys
array.
Helpful links
More of Predis
- How can I use PHP and Redis to retrieve a range of values from a sorted set?
- How can I use Predis with a cluster in PHP?
- How do I install and configure a PHP Redis DLL on a Windows machine?
- How can I install and configure PHP and Redis on a Windows system?
- How can I use the zscan command in PHP with Redis?
- How can I use PHP to increment values in Redis using ZINCRBY?
- How can I use Redis with the Yii PHP framework?
- How can I configure TLS encryption for a connection between PHP and Redis?
- How can I use PHP and Redis to retrieve data from a sorted set using ZRANGEBYSCORE?
- How do I use the PHP Redis zrevrange command?
See more codes...