class Redis (View source)

Methods

__construct(array $options = null)

Create a new Redis instance. If passed sufficient information in the options array it is also possible to connect to an instance at the same time.

__destruct()

No description

string
_compress(string $value)

Compress a value with the currently configured compressor as set with Redis::setOption().

string
_uncompress(string $value)

Uncompress the provided argument that has been compressed with the currently configured compressor as set with Redis::setOption().

string
_prefix(string $key)

Prefix the passed argument with the currently set key prefix as set with Redis::setOption().

string
_serialize(mixed $value)

Serialize the provided value with the currently set serializer as set with Redis::setOption().

mixed
_unserialize(string $value)

Unserialize the passed argument with the currently set serializer as set with Redis::setOption().

string
_pack(mixed $value)

Pack the provided value with the configured serializer and compressor as set with Redis::setOption().

mixed
_unpack(string $value)

Unpack the provided value with the configured compressor and serializer as set with Redis::setOption().

mixed
acl(string $subcmd, string ...$args)

No description

Redis|int|false
append(string $key, mixed $value)

Append data to a Redis STRING key.

Redis|bool
auth(mixed $credentials)

Authenticate a Redis connection after its been established.

Redis|bool
bgSave()

Execute a save of the Redis database in the background.

Redis|bool
bgrewriteaof()

Asynchronously rewrite Redis' append-only file

Redis|int|false
bitcount(string $key, int $start = 0, int $end = -1, bool $bybit = false)

Count the number of set bits in a Redis string.

Redis|int|false
bitop(string $operation, string $deskey, string $srckey, string ...$other_keys)

No description

Redis|int|false
bitpos(string $key, bool $bit, int $start = 0, int $end = -1, bool $bybit = false)

Return the position of the first bit set to 0 or 1 in a string.

Redis|array|null|false
blPop(string|array $key_or_keys, string|float|int $timeout_or_key, mixed ...$extra_args)

Pop an element off the beginning of a Redis list or lists, potentially blocking up to a specified timeout. This method may be called in two distinct ways, of which examples are provided below.

Redis|array|null|false
brPop(string|array $key_or_keys, string|float|int $timeout_or_key, mixed ...$extra_args)

Pop an element off of the end of a Redis list or lists, potentially blocking up to a specified timeout.

Redis|string|false
brpoplpush(string $src, string $dst, int|float $timeout)

Pop an element from the end of a Redis list, pushing it to the beginning of another Redis list, optionally blocking up to a specified timeout.

Redis|array|false
bzPopMax(string|array $key, string|int $timeout_or_key, mixed ...$extra_args)

POP the maximum scoring element off of one or more sorted sets, blocking up to a specified timeout if no elements are available.

Redis|array|false
bzPopMin(string|array $key, string|int $timeout_or_key, mixed ...$extra_args)

POP the minimum scoring element off of one or more sorted sets, blocking up to a specified timeout if no elements are available

Redis|array|null|false
bzmpop(float $timeout, array $keys, string $from, int $count = 1)

POP one or more elements from one or more sorted sets, blocking up to a specified amount of time when no elements are available.

Redis|array|null|false
zmpop(array $keys, string $from, int $count = 1)

POP one or more of the highest or lowest scoring elements from one or more sorted sets.

Redis|array|null|false
blmpop(float $timeout, array $keys, string $from, int $count = 1)

Pop one or more elements from one or more Redis LISTs, blocking up to a specified timeout when no elements are available.

Redis|array|null|false
lmpop(array $keys, string $from, int $count = 1)

Pop one or more elements off of one or more Redis LISTs.

bool
clearLastError()

Reset any last error on the connection to NULL

mixed
client(string $opt, mixed ...$args)

No description

bool
close()

No description

mixed
command(string $opt = null, string|array $arg)

No description

mixed
config(string $operation, array|string|null $key_or_settings = NULL, string|null $value = NULL)

Execute the Redis CONFIG command in a variety of ways.

bool
connect(string $host, int $port = 6379, float $timeout = 0, string $persistent_id = null, int $retry_interval = 0, float $read_timeout = 0, array $context = null)

No description

Redis|bool
copy(string $src, string $dst, array $options = null)

Make a copy of a key.

Redis|int|false
dbSize()

Return the number of keys in the currently selected Redis database.

Redis|string
debug(string $key)

No description

Redis|int|false
decr(string $key, int $by = 1)

Decrement a Redis integer by 1 or a provided value.

Redis|int|false
decrBy(string $key, int $value)

Decrement a redis integer by a value

Redis|int|false
del(array|string $key, string ...$other_keys)

Delete one or more keys from Redis.

Redis|int|false
delete(array|string $key, string ...$other_keys) deprecated

No description

Redis|bool
discard()

Discard a transaction currently in progress.

Redis|string
dump(string $key)

Dump Redis' internal binary representation of a key.

Redis|string|false
echo(string $str)

Have Redis repeat back an arbitrary string to the client.

mixed
eval(string $script, array $args = [], int $num_keys = 0)

Execute a LUA script on the redis server.

mixed
eval_ro(string $script_sha, array $args = [], int $num_keys = 0)

This is simply the read-only variant of eval, meaning the underlying script may not modify data in redis.

mixed
evalsha(string $sha1, array $args = [], int $num_keys = 0)

Execute a LUA script on the server but instead of sending the script, send the SHA1 hash of the script.

mixed
evalsha_ro(string $sha1, array $args = [], int $num_keys = 0)

This is simply the read-only variant of evalsha, meaning the underlying script may not modify data in redis.

Redis|array|false
exec()

Execute either a MULTI or PIPELINE block and return the array of replies.

Redis|int|bool
exists(mixed $key, mixed ...$other_keys)

Test if one or more keys exist.

Redis|bool
expire(string $key, int $timeout, string|null $mode = NULL)

Sets an expiration in seconds on the key in question. If connected to redis-server >= 7.0.0 you may send an additional "mode" argument which modifies how the command will execute.

Redis|bool
expireAt(string $key, int $timestamp, string|null $mode = NULL)

Set a key to expire at an exact unix timestamp.

Redis|bool
failover(array|null $to = null, bool $abort = false, int $timeout = 0)

No description

Redis|int|false
expiretime(string $key)

Get the expiration of a given key as a unix timestamp

Redis|int|false
pexpiretime(string $key)

Get the expriation timestamp of a given Redis key but in milliseconds.

Redis|bool
flushAll(bool|null $sync = null)

Deletes every key in all Redis databases

Redis|bool
flushDB(bool|null $sync = null)

Deletes all the keys of the currently selected database.

Redis|int|false
geoadd(string $key, float $lng, float $lat, string $member, mixed ...$other_triples_and_options)

No description

Redis|float|false
geodist(string $key, string $src, string $dst, string|null $unit = null)

No description

Redis|array|false
geohash(string $key, string $member, string ...$other_members)

No description

Redis|array|false
geopos(string $key, string $member, string ...$other_members)

No description

mixed
georadius(string $key, float $lng, float $lat, float $radius, string $unit, array $options = [])

No description

mixed
georadius_ro(string $key, float $lng, float $lat, float $radius, string $unit, array $options = [])

No description

mixed
georadiusbymember(string $key, string $member, float $radius, string $unit, array $options = [])

No description

mixed
georadiusbymember_ro(string $key, string $member, float $radius, string $unit, array $options = [])

No description

array
geosearch(string $key, array|string $position, array|int|float $shape, string $unit, array $options = [])

No description

Redis|array|int|false
geosearchstore(string $dst, string $src, array|string $position, array|int|float $shape, string $unit, array $options = [])

No description

mixed
get(string $key)

No description

mixed
getAuth()

Get the authentication information on the connection, if any.

Redis|int|false
getBit(string $key, int $idx)

No description

Redis|string|bool
getEx(string $key, array $options = [])

No description

int
getDBNum()

Get the database number PhpRedis thinks we're connected to.

Redis|string|bool
getDel(string $key)

No description

string
getHost()

Return the host or Unix socket we are connected to.

string|null
getLastError()

Get the last error returned to us from Redis, if any.

int
getMode()

Returns whether the connection is in ATOMIC, MULTI, or PIPELINE mode

mixed
getOption(int $option)

Retrieve the value of a configuration setting as set by Redis::setOption()

string|null
getPersistentID()

Get the persistent connection ID, if there is one.

int
getPort()

Get the port we are connected to. This number will be zero if we are connected to a unix socket.

Redis|string|false
getRange(string $key, int $start, int $end)

Retrieve a substring of a string by index.

Redis|string|array|int|false
lcs(string $key1, string $key2, array|null $options = NULL)

Get the longest common subsequence between two string keys.

float
getReadTimeout()

Get the currently set read timeout on the connection.

Redis|string|false
getset(string $key, mixed $value)

Sets a key and returns any previously set value, if the key already existed.

float|false
getTimeout()

Retrieve any set connection timeout

int|false
getTransferredBytes()

No description

Redis|int|false
hDel(string $key, string $field, string ...$other_fields)

Remove one or more fields from a hash.

Redis|bool
hExists(string $key, string $field)

Checks whether a field exists in a hash.

mixed
hGet(string $key, string $member)

No description

Redis|array|false
hGetAll(string $key)

Read every field and value from a hash.

Redis|int|false
hIncrBy(string $key, string $field, int $value)

Increment a hash field's value by an integer

Redis|float|false
hIncrByFloat(string $key, string $field, float $value)

Increment a hash field by a floating point value

Redis|array|false
hKeys(string $key)

Retrieve all of the fields of a hash.

Redis|int|false
hLen(string $key)

Get the number of fields in a hash.

Redis|array|false
hMget(string $key, array $fields)

Get one or more fields from a hash.

Redis|bool
hMset(string $key, array $fieldvals)

Add or update one or more hash fields and values

Redis|string|array
hRandField(string $key, array $options = null)

Get one or more random field from a hash.

Redis|int|false
hSet(string $key, string $member, mixed $value)

No description

Redis|bool
hSetNx(string $key, string $field, string $value)

Set a hash field and value, but only if that field does not exist

Redis|int|false
hStrLen(string $key, string $field)

Get the string length of a hash field

Redis|array|false
hVals(string $key)

Get all of the values from a hash.

Redis|array|bool
hscan(string $key, int|null $iterator, string|null $pattern = null, int $count = 0)

Iterate over the fields and values of a hash in an incremental fashion.

Redis|int|false
incr(string $key, int $by = 1)

Increment a key's value, optionally by a specifc amount.

Redis|int|false
incrBy(string $key, int $value)

Increment a key by a specific integer value

Redis|float|false
incrByFloat(string $key, float $value)

Increment a numeric key by a floating point value.

Redis|array|false
info(string ...$sections)

Retrieve information about the connected redis-server. If no arguments are passed to this function, redis will return every info field. Alternatively you may pass a specific section you want returned (e.g. 'server', or 'memory') to receive only information pertaining to that section.

bool
isConnected()

Check if we are currently connected to a Redis instance.

Redis|array|false
keys(string $pattern)

No description

Redis|int|false
lInsert(string $key, string $pos, mixed $pivot, mixed $value)

No description

Redis|int|false
lLen(string $key)

No description

Redis|string|false
lMove(string $src, string $dst, string $wherefrom, string $whereto)

No description

Redis|bool|string|array
lPop(string $key, int $count = 0)

No description

Redis|null|bool|int|array
lPos(string $key, mixed $value, array $options = null)

No description

int|Redis
lPush(string $key, mixed ...$elements)

No description

Redis|int|false
rPush(string $key, mixed ...$elements)

No description

Redis|int|false
lPushx(string $key, mixed $value)

No description

Redis|int|false
rPushx(string $key, mixed $value)

No description

Redis|bool
lSet(string $key, int $index, mixed $value)

No description

int
lastSave()

No description

mixed
lindex(string $key, int $index)

No description

Redis|array|false
lrange(string $key, int $start, int $end)

No description

int|Redis|false
lrem(string $key, mixed $value, int $count = 0)

No description

Redis|bool
ltrim(string $key, int $start, int $end)

No description

array|Redis
mget(array $keys)

No description

Redis|bool
migrate(string $host, int $port, string|array $key, int $dstdb, int $timeout, bool $copy = false, bool $replace = false, mixed $credentials = NULL)

No description

bool
move(string $key, int $index)

No description

Redis|bool
mset(array $key_values)

No description

Redis|bool
msetnx(array $key_values)

No description

bool|Redis
multi(int $value = Redis::MULTI)

No description

Redis|int|string|false
object(string $subcommand, string $key)

No description

bool
open(string $host, int $port = 6379, float $timeout = 0, string $persistent_id = NULL, int $retry_interval = 0, float $read_timeout = 0, array $context = NULL) deprecated

No description

bool
pconnect(string $host, int $port = 6379, float $timeout = 0, string $persistent_id = NULL, int $retry_interval = 0, float $read_timeout = 0, array $context = NULL)

No description

bool
persist(string $key)

No description

bool
pexpire(string $key, int $timeout, string|null $mode = NULL)

Sets an expiration in milliseconds on a given key. If connected to Redis >= 7.0.0 you can pass an optional mode argument that modifies how the command will execute.

Redis|bool
pexpireAt(string $key, int $timestamp, string|null $mode = NULL)

Set a key's expiration to a specific Unix Timestamp in milliseconds. If connected to Redis >= 7.0.0 you can pass an optional 'mode' argument.

Redis|int
pfadd(string $key, array $elements)

Add one or more elements to a Redis HyperLogLog key

Redis|int
pfcount(string $key)

Retrieve the cardinality of a Redis HyperLogLog key.

Redis|bool
pfmerge(string $dst, array $srckeys)

Merge one or more source HyperLogLog sets into a destination set.

Redis|string|bool
ping(string $message = NULL)

PING the redis server with an optional string argument.

bool|Redis
pipeline()

Enter into pipeline mode.

bool
popen(string $host, int $port = 6379, float $timeout = 0, string $persistent_id = NULL, int $retry_interval = 0, float $read_timeout = 0, array $context = NULL) deprecated

No description

bool|Redis
psetex(string $key, int $expire, mixed $value)

No description

bool
psubscribe(array $patterns, callable $cb)

Subscribe to one or more glob-style patterns

Redis|int|false
pttl(string $key)

Get a keys time to live in milliseconds.

Redis|int|false
publish(string $channel, string $message)

Publish a message to a pubsub channel

mixed
pubsub(string $command, mixed $arg = null)

No description

Redis|array|bool
punsubscribe(array $patterns)

Unsubscribe from one or more channels by pattern

Redis|array|string|bool
rPop(string $key, int $count = 0)

Pop one or more elements from the end of a list.

Redis|string|false
randomKey()

Return a random key from the current database

mixed
rawcommand(string $command, mixed ...$args)

Execute any arbitrary Redis command by name.

Redis|bool
rename(string $old_name, string $new_name)

Unconditionally rename a key from $old_name to $new_name

Redis|bool
renameNx(string $key_src, string $key_dst)

Renames $key_src to $key_dst but only if newkey does not exist.

Redis|bool
reset()

Reset the state of the connection.

Redis|bool
restore(string $key, int $ttl, string $value, array|null $options = NULL)

Restore a key by the binary payload generated by the DUMP command.

mixed
role()

Query whether the connected instance is a primary or replica

Redis|string|false
rpoplpush(string $srckey, string $dstkey)

Atomically pop an element off the end of a Redis LIST and push it to the beginning of another.

Redis|int|false
sAdd(string $key, mixed $value, mixed ...$other_values)

Add one or more values to a Redis SET key.

int
sAddArray(string $key, array $values)

Add one ore more values to a Redis SET key. This is an alternative to Redis::sadd() but instead of being variadic, takes a single array of values.

Redis|array|false
sDiff(string $key, string ...$other_keys)

Given one or more Redis SETS, this command returns all of the members from the first set that are not in any subsequent set.

Redis|int|false
sDiffStore(string $dst, string $key, string ...$other_keys)

This method performs the same operation as SDIFF except it stores the resulting diff values in a specified destination key.

Redis|array|false
sInter(array|string $key, string ...$other_keys)

Given one or more Redis SET keys, this command will return all of the elements that are in every one.

Redis|int|false
sintercard(array $keys, int $limit = -1)

Compute the intersection of one or more sets and return the cardinality of the result.

Redis|int|false
sInterStore(array|string $key, string ...$other_keys)

Perform the intersection of one or more Redis SETs, storing the result in a destination key, rather than returning them.

Redis|array|false
sMembers(string $key)

Retrieve every member from a set key.

Redis|array|false
sMisMember(string $key, string $member, string ...$other_members)

Check if one or more values are members of a set.

Redis|bool
sMove(string $src, string $dst, mixed $value)

Pop a member from one set and push it onto another. This command will create the destination set if it does not currently exist.

Redis|string|array|false
sPop(string $key, int $count = 0)

Remove one or more elements from a set.

Redis|string|array|false
sRandMember(string $key, int $count = 0)

Retrieve one or more random members of a set.

Redis|array|false
sUnion(string $key, string ...$other_keys)

Returns the union of one or more Redis SET keys.

Redis|int|false
sUnionStore(string $dst, string $key, string ...$other_keys)

Perform a union of one or more Redis SET keys and store the result in a new set

Redis|bool
save()

Persist the Redis database to disk. This command will block the server until the save is completed. For a nonblocking alternative, see Redis::bgsave().

array|false
scan(int|null $iterator, string|null $pattern = null, int $count = 0, string $type = NULL)

Incrementally scan the Redis keyspace, with optional pattern and type matching.

Redis|int|false
scard(string $key)

Retrieve the number of members in a Redis set.

mixed
script(string $command, mixed ...$args)

An administrative command used to interact with LUA scripts stored on the server.

Redis|bool
select(int $db)

Select a specific Redis database.

Redis|string|bool
set(string $key, mixed $value, mixed $options = NULL)

Create or set a Redis STRING key to a value.

Redis|int|false
setBit(string $key, int $idx, bool $value)

Set a specific bit in a Redis string to zero or one

Redis|int|false
setRange(string $key, int $index, string $value)

Update or append to a Redis string at a specific starting index

bool
setOption(int $option, mixed $value)

Set a configurable option on the Redis object.

Redis|bool
setex(string $key, int $expire, mixed $value)

Set a Redis STRING key with a specific expiration in seconds.

Redis|bool
setnx(string $key, mixed $value)

Set a key to a value, but only if that key does not already exist.

Redis|bool
sismember(string $key, mixed $value)

Check whether a given value is the member of a Redis SET.

Redis|bool
slaveof(string $host = NULL, int $port = 6379) deprecated

Turn a redis instance into a replica of another or promote a replica to a primary.

Redis|bool
replicaof(string $host = NULL, int $port = 6379)

Used to turn a Redis instance into a replica of another, or to remove replica status promoting the instance to a primary.

Redis|int|false
touch(array|string $key_or_array, string ...$more_keys)

Update one or more keys last modified metadata.

mixed
slowlog(string $operation, int $length = 0)

Interact with Redis' slowlog functionality in various ways, depending on the value of 'operation'.

mixed
sort(string $key, array|null $options = null)

Sort the contents of a Redis key in various ways.

mixed
sort_ro(string $key, array|null $options = null)

This is simply a read-only variant of the sort command

array
sortAsc(string $key, string|null $pattern = null, mixed $get = null, int $offset = -1, int $count = -1, string|null $store = null) deprecated

No description

array
sortAscAlpha(string $key, string|null $pattern = null, mixed $get = null, int $offset = -1, int $count = -1, string|null $store = null) deprecated

No description

array
sortDesc(string $key, string|null $pattern = null, mixed $get = null, int $offset = -1, int $count = -1, string|null $store = null) deprecated

No description

array
sortDescAlpha(string $key, string|null $pattern = null, mixed $get = null, int $offset = -1, int $count = -1, string|null $store = null) deprecated

No description

Redis|int|false
srem(string $key, mixed $value, mixed ...$other_values)

Remove one or more values from a Redis SET key.

array|false
sscan(string $key, int|null $iterator, string|null $pattern = null, int $count = 0)

Scan the members of a redis SET key.

Redis|int|false
strlen(string $key)

Retrieve the length of a Redis STRING key.

bool
subscribe(array $channels, callable $cb)

Subscribe to one or more Redis pubsub channels.

Redis|bool
swapdb(int $src, int $dst)

Atomically swap two Redis databases so that all of the keys in the source database will now be in the destination database and vice-versa.

Redis|array
time()

Retrieve the server time from the connected Redis instance.

Redis|int|false
ttl(string $key)

Get the amount of time a Redis key has before it will expire, in seconds.

Redis|int|false
type(string $key)

Get the type of a given Redis key.

Redis|int|false
unlink(array|string $key, string ...$other_keys)

Delete one or more keys from the Redis database. Unlike this operation, the actual deletion is asynchronous, meaning it is safe to delete large keys without fear of Redis blocking for a long period of time.

Redis|array|bool
unsubscribe(array $channels)

Unsubscribe from one or more subscribed channels.

Redis|bool
unwatch()

Remove any previously WATCH'ed keys in a transaction.

bool|Redis
watch(array|string $key, string ...$other_keys)

No description

int|false
wait(int $numreplicas, int $timeout)

Block the client up to the provided timeout until a certain number of replicas have confirmed recieving them.

int|false
xack(string $key, string $group, array $ids)

No description

Redis|string|false
xadd(string $key, string $id, array $values, int $maxlen = 0, bool $approx = false, bool $nomkstream = false)

Append a message to a stream.

Redis|bool|array
xautoclaim(string $key, string $group, string $consumer, int $min_idle, string $start, int $count = -1, bool $justid = false)

No description

Redis|bool|array
xclaim(string $key, string $group, string $consumer, int $min_idle, array $ids, array $options)

No description

Redis|int|false
xdel(string $key, array $ids)

Remove one or more specific IDs from a stream.

mixed
xgroup(string $operation, string $key = null, string $group = null, string $id_or_consumer = null, bool $mkstream = false, int $entries_read = -2)

XGROUP

mixed
xinfo(string $operation, string|null $arg1 = null, string|null $arg2 = null, int $count = -1)

Retrieve information about a stream key.

Redis|int|false
xlen(string $key)

Get the number of messages in a Redis STREAM key.

Redis|array|false
xpending(string $key, string $group, string|null $start = null, string|null $end = null, int $count = -1, string|null $consumer = null)

Interact with stream messages that have been consumed by a consumer group but not yet acknowledged with XACK.

Redis|array|bool
xrange(string $key, string $start, string $end, int $count = -1)

Get a range of entries from a STREAM key.

Redis|array|bool
xread(array $streams, int $count = -1, int $block = -1)

Consume one or more unconsumed elements in one or more streams.

Redis|array|bool
xreadgroup(string $group, string $consumer, array $streams, int $count = 1, int $block = 1)

Read one or more messages using a consumer group.

Redis|array|bool
xrevrange(string $key, string $end, string $start, int $count = -1)

Get a range of entries from a STREAM ke in reverse cronological order.

Redis|int|false
xtrim(string $key, string $threshold, bool $approx = false, bool $minid = false, int $limit = -1)

Truncate a STREAM key in various ways.

Redis|int|false
zAdd(string $key, array|float $score_or_options, mixed ...$more_scores_and_mems)

Add one or more elements and scores to a Redis sorted set.

Redis|int|false
zCard(string $key)

Return the number of elements in a sorted set.

Redis|int|false
zCount(string $key, string $start, string $end)

Count the number of members in a sorted set with scores inside a provided range.

Redis|float|false
zIncrBy(string $key, float $value, mixed $member)

Create or increment the score of a member in a Redis sorted set

Redis|int|false
zLexCount(string $key, string $min, string $max)

Count the number of elements in a sorted set whos members fall within the provided lexographical range.

Redis|array|false
zMscore(string $key, mixed $member, mixed ...$other_members)

Retrieve the score of one or more members in a sorted set.

Redis|array|false
zPopMax(string $key, int $count = null)

Pop one or more of the highest scoring elements from a sorted set.

Redis|array|false
zPopMin(string $key, int $count = null)

Pop one or more of the lowest scoring elements from a sorted set.

Redis|array|false
zRange(string $key, mixed $start, mixed $end, array|bool|null $options = null)

Retrieve a range of elements of a sorted set between a start and end point.

Redis|array|false
zRangeByLex(string $key, string $min, string $max, int $offset = -1, int $count = -1)

Retrieve a range of elements from a sorted set by legographical range.

Redis|array|false
zRangeByScore(string $key, string $start, string $end, array $options = [])

Retrieve a range of members from a sorted set by their score.

Redis|int|false
zrangestore(string $dstkey, string $srckey, string $start, string $end, array|bool|null $options = NULL)

This command is similar to ZRANGE except that instead of returning the values directly it will store them in a destination key provided by the user

Redis|string|array
zRandMember(string $key, array $options = null)

Retrieve one or more random members from a Redis sorted set.

Redis|int|false
zRank(string $key, mixed $member)

Get the rank of a member of a sorted set, by score.

Redis|int|false
zRem(mixed $key, mixed $member, mixed ...$other_members)

Remove one or more members from a Redis sorted set.

Redis|int|false
zRemRangeByLex(string $key, string $min, string $max)

Remove zero or more elements from a Redis sorted set by legographical range.

Redis|int|false
zRemRangeByRank(string $key, int $start, int $end)

Remove one or more members of a sorted set by their rank.

Redis|int|false
zRemRangeByScore(string $key, string $start, string $end)

Remove one or more members of a sorted set by their score.

Redis|array|false
zRevRange(string $key, int $start, int $end, mixed $scores = null)

List the members of a Redis sorted set in reverse order

Redis|array|false
zRevRangeByLex(string $key, string $max, string $min, int $offset = -1, int $count = -1)

List members of a Redis sorted set within a legographical range, in reverse order.

Redis|array|false
zRevRangeByScore(string $key, string $max, string $min, array|bool $options = [])

List elements from a Redis sorted set by score, highest to lowest

Redis|int|false
zRevRank(string $key, mixed $member)

Retrieve a member of a sorted set by reverse rank.

Redis|float|false
zScore(string $key, mixed $member)

Get the score of a member of a sorted set.

Redis|array|false
zdiff(array $keys, array $options = null)

Given one or more sorted set key names, return every element that is in the first set but not any of the others.

Redis|int|false
zdiffstore(string $dst, array $keys)

Store the difference of one or more sorted sets in a destination sorted set.

Redis|array|false
zinter(array $keys, array|null $weights = null, array|null $options = null)

Compute the intersection of one or more sorted sets and return the members

Redis|int|false
zintercard(array $keys, int $limit = -1)

Similar to ZINTER but instead of returning the intersected values, this command returns the cardinality of the intersected set.

Redis|int|false
zinterstore(string $dst, array $keys, array|null $weights = null, string|null $aggregate = null)

Compute the intersection of one ore more sorted sets storing the result in a new sorted set.

Redis|array|false
zscan(string $key, int|null $iterator, string|null $pattern = null, int $count = 0)

Scan the members of a sorted set incrementally, using a cursor

Redis|array|false
zunion(array $keys, array|null $weights = null, array|null $options = null)

Retrieve the union of one or more sorted sets

Redis|int|false
zunionstore(string $dst, array $keys, array|null $weights = NULL, string|null $aggregate = NULL)

Perform a union on one or more Redis sets and store the result in a destination sorted set.

Details

Redis __construct(array $options = null)

Create a new Redis instance. If passed sufficient information in the options array it is also possible to connect to an instance at the same time.

NOTE: Below is an example options array with various setting

$options = [
    'host'           => 'localhost',
    'port'           => 6379,
    'readTimeout'    => 2.5,
    'connectTimeout' => 2.5,
    'persistent'     => true,

    // Valid formats: NULL, ['user', 'pass'], 'pass', or ['pass']
    'auth' => ['phpredis', 'phpredis'],

    // See PHP stream options for valid SSL configuration settings.
    'ssl' => ['verify_peer' => false],

    // How quickly to retry a connection after we time out or it  closes.
    // Note that this setting is overridden by 'backoff' strategies.
    'retryInterval'  => 100,

     // Which backoff algorithm to use.  'decorrelated jitter' is
     // likely the best one for most solution, but there are many
     // to choose from:
     //     REDIS_BACKOFF_ALGORITHM_DEFAULT
     //     REDIS_BACKOFF_ALGORITHM_CONSTANT
     //     REDIS_BACKOFF_ALGORITHM_UNIFORM
     //     REDIS_BACKOFF_ALGORITHM_EXPONENTIAL
     //     REDIS_BACKOFF_ALGORITHM_FULL_JITTER
     //     REDIS_BACKOFF_ALGORITHM_EQUAL_JITTER
     //     REDIS_BACKOFF_ALGORITHM_DECORRELATED_JITTER
     // 'base', and 'cap' are in milliseconds and represent the first
     // delay redis will use when reconnecting, and the maximum delay
     // we will reach while retrying.
    'backoff' => [
        'algorithm' => Redis::BACKOFF_ALGORITHM_DECORRELATED_JITTER,
        'base'      => 500,
        'cap'       => 750,
    ]
];

Note: If you do wish to connect via the constructor, only 'host' is strictly required, which will cause PhpRedis to connect to that host on Redis' default port (6379).

__destruct()

No description

string _compress(string $value)

Compress a value with the currently configured compressor as set with Redis::setOption().

Parameters

string $value

The value to be compressed

Return Value

string

The compressed result

See also

Redis::setOption

string _uncompress(string $value)

Uncompress the provided argument that has been compressed with the currently configured compressor as set with Redis::setOption().

Parameters

string $value

The compressed value to uncompress.

Return Value

string

The uncompressed result.

See also

Redis::setOption

string _prefix(string $key)

Prefix the passed argument with the currently set key prefix as set with Redis::setOption().

Parameters

string $key

The key/string to prefix

Return Value

string

The prefixed string

string _serialize(mixed $value)

Serialize the provided value with the currently set serializer as set with Redis::setOption().

Parameters

mixed $value

The value to serialize

Return Value

string

The serialized result

See also

Redis::setOption

mixed _unserialize(string $value)

Unserialize the passed argument with the currently set serializer as set with Redis::setOption().

Parameters

string $value

The value to unserialize

Return Value

mixed

The unserialized result

See also

Redis::setOption

string _pack(mixed $value)

Pack the provided value with the configured serializer and compressor as set with Redis::setOption().

Parameters

mixed $value

The value to pack

Return Value

string

The packed result having been serialized and compressed.

mixed _unpack(string $value)

Unpack the provided value with the configured compressor and serializer as set with Redis::setOption().

Parameters

string $value

The value which has been serialized and compressed.

Return Value

mixed

The uncompressed and eserialized value.

mixed acl(string $subcmd, string ...$args)

No description

Parameters

string $subcmd
string ...$args

Return Value

mixed

Redis|int|false append(string $key, mixed $value)

Append data to a Redis STRING key.

$redis = new Redis(['host' => 'localhost']);
$redis->set('foo', 'hello);
var_dump($redis->append('foo', 'world'));

Parameters

string $key

The key in question

mixed $value

The data to append to the key.

Return Value

Redis|int|false

The new string length of the key or false on failure.

Redis|bool auth(mixed $credentials)

Authenticate a Redis connection after its been established.

$redis->auth('password'); $redis->auth(['password']); $redis->auth(['username', 'password']);

Parameters

mixed $credentials

A string password, or an array with one or two string elements.

Return Value

Redis|bool

Whether the AUTH was successful.

See also

https://redis.io/commands/auth

Redis|bool bgSave()

Execute a save of the Redis database in the background.

Return Value

Redis|bool

Whether the command was successful.

See also

https://redis.io/commands/bgsave

Redis|bool bgrewriteaof()

Asynchronously rewrite Redis' append-only file

Return Value

Redis|bool

Whether the command was successful.

See also

https://redis.io/commands/bgrewriteaof

Redis|int|false bitcount(string $key, int $start = 0, int $end = -1, bool $bybit = false)

Count the number of set bits in a Redis string.

Parameters

string $key

The key in question (must be a string key)

int $start

The index where Redis should start counting. If omitted it defaults to zero, which means the start of the string.

int $end

The index where Redis should stop counting. If omitted it defaults to -1, meaning the very end of the string.

bool $bybit

Whether or not Redis should treat $start and $end as bit positions, rather than bytes.

Return Value

Redis|int|false

The number of bits set in the requested range.

See also

https://redis.io/commands/bitcount/

Redis|int|false bitop(string $operation, string $deskey, string $srckey, string ...$other_keys)

No description

Parameters

string $operation
string $deskey
string $srckey
string ...$other_keys

Return Value

Redis|int|false

Redis|int|false bitpos(string $key, bool $bit, int $start = 0, int $end = -1, bool $bybit = false)

Return the position of the first bit set to 0 or 1 in a string.

Parameters

string $key

The key to check (must be a string)

bool $bit

Whether to look for an unset (0) or set (1) bit.

int $start

Where in the string to start looking.

int $end

Where in the string to stop looking.

bool $bybit

If true, Redis will treat $start and $end as BIT values and not bytes, so if start was 0 and end was 2, Redis would only search the first two bits.

Return Value

Redis|int|false

The position of the first set or unset bit.

See also

https://redis.io/commands/bitpos/

Redis|array|null|false blPop(string|array $key_or_keys, string|float|int $timeout_or_key, mixed ...$extra_args)

Pop an element off the beginning of a Redis list or lists, potentially blocking up to a specified timeout. This method may be called in two distinct ways, of which examples are provided below.

Parameters

string|array $key_or_keys

This can either be a string key or an array of one or more keys.

string|float|int $timeout_or_key

If the previous argument was a string key, this can either be an additional key, or the timeout you wish to send to the command.

mixed ...$extra_args

Return Value

Redis|array|null|false

Can return various things depending on command and data in Redis.

See also

https://redis.io/commands/blpop/

Examples

$redis->blPop('list1', 'list2', 'list3', 1.5);
$relay->blPop(['list1', 'list2', 'list3'], 1.5);

Redis|array|null|false brPop(string|array $key_or_keys, string|float|int $timeout_or_key, mixed ...$extra_args)

Pop an element off of the end of a Redis list or lists, potentially blocking up to a specified timeout.

The calling convention is identical to Redis::blPop() so see that documentation for more details.

Parameters

string|array $key_or_keys
string|float|int $timeout_or_key
mixed ...$extra_args

Return Value

Redis|array|null|false

See also

https://redis.io/commands/brpop/
Redis::blPop

Redis|string|false brpoplpush(string $src, string $dst, int|float $timeout)

Pop an element from the end of a Redis list, pushing it to the beginning of another Redis list, optionally blocking up to a specified timeout.

Parameters

string $src

The source list

string $dst

The destination list

int|float $timeout

The number of seconds to wait. Note that you must be connected to Redis >= 6.0.0 to send a floating point timeout.

Return Value

Redis|string|false

See also

https://redis.io/commands/brpoplpush/

Redis|array|false bzPopMax(string|array $key, string|int $timeout_or_key, mixed ...$extra_args)

POP the maximum scoring element off of one or more sorted sets, blocking up to a specified timeout if no elements are available.

Following are examples of the two main ways to call this method.

NOTE: We reccomend calling this function with an array and a timeout as the other strategy may be deprecated in future versions of PhpRedis

Parameters

string|array $key
string|int $timeout_or_key

If the previous argument was an array, this argument must be a timeout value. Otherwise it could also be another key.

mixed ...$extra_args

Can consist of additional keys, until the last argument which needs to be a timeout.

Return Value

Redis|array|false

The popped elements.

See also

https://redis.io/commands/bzpopmax

Examples

$redis->bzPopMax('key1', 'key2', 'key3', 1.5);
$redis->bzPopMax(['key1', 'key2', 'key3'], 1.5);

Redis|array|false bzPopMin(string|array $key, string|int $timeout_or_key, mixed ...$extra_args)

POP the minimum scoring element off of one or more sorted sets, blocking up to a specified timeout if no elements are available

This command is identical in semantics to bzPopMax so please see that method for more information.

Parameters

string|array $key
string|int $timeout_or_key
mixed ...$extra_args

Return Value

Redis|array|false

See also

https://redis.io/commands/bzpopmin
Redis::bzPopMax

Redis|array|null|false bzmpop(float $timeout, array $keys, string $from, int $count = 1)

POP one or more elements from one or more sorted sets, blocking up to a specified amount of time when no elements are available.

Parameters

float $timeout

How long to block if there are no element available

array $keys

The sorted sets to pop from

string $from

The string 'MIN' or 'MAX' (case insensitive) telling Redis whether you wish to pop the lowest or highest scoring members from the set(s).

int $count

Pop up to how many elements.

Return Value

Redis|array|null|false

This function will return an array of popped elements, or false depending on whether any elements could be popped within the specified timeout.

NOTE: If Redis::OPT_NULL_MULTIBULK_AS_NULL is set to true via Redis::setOption(), this method will instead return NULL when Redis doesn't pop any elements.

Redis|array|null|false zmpop(array $keys, string $from, int $count = 1)

POP one or more of the highest or lowest scoring elements from one or more sorted sets.

Parameters

array $keys

One or more sorted sets

string $from

The string 'MIN' or 'MAX' (case insensitive) telling Redis whether you want to pop the lowest or highest scoring elements.

int $count

Pop up to how many elements at once.

Return Value

Redis|array|null|false

An array of popped elements or false if none could be popped.

See also

https://redis.io/commands/zmpop

Redis|array|null|false blmpop(float $timeout, array $keys, string $from, int $count = 1)

Pop one or more elements from one or more Redis LISTs, blocking up to a specified timeout when no elements are available.

Parameters

float $timeout

The number of seconds Redis will block when no elements are available.

array $keys

One or more Redis LISTs to pop from.

string $from

The string 'LEFT' or 'RIGHT' (case insensitive), telling Redis whether to pop elements from the beginning or end of the LISTs.

int $count

Pop up to how many elements at once.

Return Value

Redis|array|null|false

One or more elements popped from the list(s) or false if all LISTs were empty.

See also

https://redis.io/commands/blmpop

Redis|array|null|false lmpop(array $keys, string $from, int $count = 1)

Pop one or more elements off of one or more Redis LISTs.

Parameters

array $keys

An array with one or more Redis LIST key names.

string $from

The string 'LEFT' or 'RIGHT' (case insensitive), telling Redis whether to pop\ elements from the beginning or end of the LISTs.

int $count

The maximum number of elements to pop at once.

Return Value

Redis|array|null|false

One or more elements popped from the LIST(s) or false if all the LISTs were empty.

See also

https://redis.io/commands/lmpop

bool clearLastError()

Reset any last error on the connection to NULL

Return Value

bool

This should always return true or throw an exception if we're not connected.

See also

Redis::getLastError

Examples

$redis = new Redis(['host' => 'localhost']);
$redis->set('string', 'this_is_a_string');
$redis->smembers('string');
var_dump($redis->getLastError());
$redis->clearLastError();
var_dump($redis->getLastError());

mixed client(string $opt, mixed ...$args)

No description

Parameters

string $opt
mixed ...$args

Return Value

mixed

bool close()

No description

Return Value

bool

mixed command(string $opt = null, string|array $arg)

No description

Parameters

string $opt
string|array $arg

Return Value

mixed

mixed config(string $operation, array|string|null $key_or_settings = NULL, string|null $value = NULL)

Execute the Redis CONFIG command in a variety of ways.

What the command does in particular depends on the $operation qualifier. Operations that PhpRedis supports are: RESETSTAT, REWRITE, GET, and SET.

Parameters

string $operation

The CONFIG operation to execute (e.g. GET, SET, REWRITE).

array|string|null $key_or_settings

One or more keys or values.

string|null $value

The value if this is a CONFIG SET operation.

Return Value

mixed

See also

https://redis.io/commands/config

Examples

$redis->config('GET', 'timeout');
$redis->config('GET', ['timeout', 'databases']);
$redis->config('SET', 'timeout', 30);
$redis->config('SET', ['timeout' => 30, 'loglevel' => 'warning']);

bool connect(string $host, int $port = 6379, float $timeout = 0, string $persistent_id = null, int $retry_interval = 0, float $read_timeout = 0, array $context = null)

No description

Parameters

string $host
int $port
float $timeout
string $persistent_id
int $retry_interval
float $read_timeout
array $context

Return Value

bool

Redis|bool copy(string $src, string $dst, array $options = null)

Make a copy of a key.

$redis = new Redis(['host' => 'localhost']);

Parameters

string $src

The key to copy

string $dst

The name of the new key created from the source key.

array $options

An array with modifiers on how COPY should operate.

$options = [
    'REPLACE' => true|false // Whether to replace an existing key.
    'DB' => int             // Copy key to specific db.
];

Return Value

Redis|bool

True if the copy was completed and false if not.

See also

https://redis.io/commands/copy

Examples

$redis->pipeline()
->select(1)
->del('newkey')
->select(0)
->del('newkey')
->mset(['source1' => 'value1', 'exists' => 'old_value'])
->exec();

var_dump($redis->copy('source1', 'newkey'));
var_dump($redis->copy('source1', 'newkey', ['db' => 1]));
var_dump($redis->copy('source1', 'exists'));
var_dump($redis->copy('source1', 'exists', ['REPLACE' => true]));

Redis|int|false dbSize()

Return the number of keys in the currently selected Redis database.

Return Value

Redis|int|false

The number of keys or false on failure.

See also

https://redis.io/commands/dbsize

Examples

$redis = new Redis(['host' => 'localhost']);
$redis->flushdb();
$redis->set('foo', 'bar');
var_dump($redis->dbsize());
$redis->mset(['a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd']);
var_dump($redis->dbsize());

Redis|string debug(string $key)

No description

Parameters

string $key

Return Value

Redis|string

Redis|int|false decr(string $key, int $by = 1)

Decrement a Redis integer by 1 or a provided value.

$redis = new Redis(['host' => 'localhost']);

$redis->set('counter', 3);

var_dump($redis->decr('counter'));
var_dump($redis->decr('counter', 2));

Parameters

string $key

The key to decrement

int $by

How much to decrement the key. Note that if this value is not sent or is set to 1, PhpRedis will actually invoke the 'DECR' command. If it is any value other than 1 PhpRedis will actually send the DECRBY command.

Return Value

Redis|int|false

The new value of the key or false on failure.

See also

https://redis.io/commands/decr
https://redis.io/commands/decrby

Redis|int|false decrBy(string $key, int $value)

Decrement a redis integer by a value

$redis = new Redis(['host' => 'localhost');

$redis->set('counter', 3);
var_dump($redis->decrby('counter', 1));
var_dump($redis->decrby('counter', 2));

Parameters

string $key

The integer key to decrement.

int $value

How much to decrement the key.

Return Value

Redis|int|false

The new value of the key or false on failure.

See also

https://redis.io/commands/decrby

Redis|int|false del(array|string $key, string ...$other_keys)

Delete one or more keys from Redis.

This method can be called in two distinct ways. The first is to pass a single array of keys to delete, and the second is to pass N arguments, all names of keys. See below for an example of both strategies.

$redis = new Redis(['host' => 'localhost']);

for ($i = 0; $i < 5; $i++) {
    $redis->set("key:$i", "val:$i");
}

var_dump($redis->del('key:0', 'key:1'));
var_dump($redis->del(['key:2', 'key:3', 'key:4']));

Parameters

array|string $key
string ...$other_keys

One or more additional keys passed in a variadic fashion.

Return Value

Redis|int|false

The number of keys that were deleted

See also

https://redis.io/commands/del

Redis|int|false delete(array|string $key, string ...$other_keys) deprecated

deprecated

No description

Parameters

array|string $key
string ...$other_keys

Return Value

Redis|int|false

Redis|bool discard()

Discard a transaction currently in progress.

$redis = new Redis(['host' => 'localhost']);

$redis->multi()->set('foo', 'bar')->get('foo');

// Redis::MULTI
$redis->getMode();

// Discard the in-progress transaction
$redis->discard();

// Redis::ATOMIC
$redis->getMode();

Return Value

Redis|bool

True if we could discard the transaction.

Redis|string dump(string $key)

Dump Redis' internal binary representation of a key.

$redis = new Redis(['host' => 'localhost']);

$redis->del('zset');

$redis->zadd('zset', 0, 'zero', 1, 'one', 2, 'two');

// Retrieve the binary representation of the zset
$binary = $redis->dump('zset');

// Retore it to a different name
$redis->restore('new-zset', 0, $binary);

$redis->zRange('new-zset', 0, -1, true);

Parameters

string $key

The key to dump.

Return Value

Redis|string

A binary string representing the key's value.

See also

https://redis.io/commands/dump

Redis|string|false echo(string $str)

Have Redis repeat back an arbitrary string to the client.

$redis = new Redis(['host' => 'localhost']);

var_dump($redis->echo('Hello, World'));

Parameters

string $str

The string to echo

Return Value

Redis|string|false

The string sent to Redis or false on failure.

See also

https://redis.io/commands/echo

mixed eval(string $script, array $args = [], int $num_keys = 0)

Execute a LUA script on the redis server.

Parameters

string $script

A string containing the LUA script

array $args

An array of arguments to pass to this script

int $num_keys

How many of the arguments are keys. This is needed as redis distinguishes between key name arguments and other data.

Return Value

mixed

LUA scripts may return arbitrary data so this method can return strings, arrays, nested arrays, etc.

See also

https://redis.io/commands/eval/

mixed eval_ro(string $script_sha, array $args = [], int $num_keys = 0)

This is simply the read-only variant of eval, meaning the underlying script may not modify data in redis.

Parameters

string $script_sha
array $args
int $num_keys

Return Value

mixed

See also

Redis::eval

mixed evalsha(string $sha1, array $args = [], int $num_keys = 0)

Execute a LUA script on the server but instead of sending the script, send the SHA1 hash of the script.

Parameters

string $sha1
array $args

Arguments to send to the script.

int $num_keys

The number of arguments that are keys

Return Value

mixed

Returns whatever the specific script does.

See also

https://redis.io/commands/evalsha/
Redis::eval

mixed evalsha_ro(string $sha1, array $args = [], int $num_keys = 0)

This is simply the read-only variant of evalsha, meaning the underlying script may not modify data in redis.

Parameters

string $sha1
array $args
int $num_keys

Return Value

mixed

See also

Redis::evalsha

Redis|array|false exec()

Execute either a MULTI or PIPELINE block and return the array of replies.

$redis = new Redis(['host' => 'localhost']);

$res = $redis->multi()
             ->set('foo', 'bar')
             ->get('foo')
             ->del('list')
             ->rpush('list', 'one', 'two', 'three')
             ->exec();

var_dump($res);

Return Value

Redis|array|false

The array of pipeline'd or multi replies or false on failure.

See also

https://redis.io/commands/exec
https://redis.io/commands/multi
Redis::pipeline
Redis::multi

Redis|int|bool exists(mixed $key, mixed ...$other_keys)

Test if one or more keys exist.

$redis = new Redis(['host' => 'localhost']);

$redis->multi()
      ->mset(['k1' => 'v1', 'k2' => 'v2', 'k3' => 'v3', 'k4' => 'v4'])
      ->exec();

// Using a single array of keys
var_dump($redis->exists(['k1', 'k2', 'k3']));

// Calling via variadic arguments
var_dump($redis->exists('k4', 'k5', 'notakey'));

// --- OUTPUT ---
// int(3)
// int(1)

Parameters

mixed $key

Either an array of keys or a string key

mixed ...$other_keys

If the previous argument was a string, you may send any number of additional keys to test.

Return Value

Redis|int|bool

The number of keys that do exist and false on failure

See also

https://redis.io/commands/exists

Redis|bool expire(string $key, int $timeout, string|null $mode = NULL)

Sets an expiration in seconds on the key in question. If connected to redis-server >= 7.0.0 you may send an additional "mode" argument which modifies how the command will execute.

Parameters

string $key

The key to set an expiration on.

int $timeout
string|null $mode

A two character modifier that changes how the command works.

NX - Set expiry only if key has no expiry
XX - Set expiry only if key has an expiry
LT - Set expiry only when new expiry is < current expiry
GT - Set expiry only when new expiry is > current expiry

Return Value

Redis|bool

True if an expiration was set and false otherwise.

See also

https://redis.io/commands/expire

Redis|bool expireAt(string $key, int $timestamp, string|null $mode = NULL)

Set a key to expire at an exact unix timestamp.

Parameters

string $key

The key to set an expiration on.

int $timestamp

The unix timestamp to expire at.

string|null $mode

An option 'mode' that modifies how the command acts (see Redis::expire).

Return Value

Redis|bool

True if an expiration was set, false if not.

See also

https://redis.io/commands/expireat
https://redis.io/commands/expire
Redis::expire

Redis|bool failover(array|null $to = null, bool $abort = false, int $timeout = 0)

No description

Parameters

array|null $to
bool $abort
int $timeout

Return Value

Redis|bool

Redis|int|false expiretime(string $key)

Get the expiration of a given key as a unix timestamp

$redis = new Redis(['host' => 'localhost']);

$redis->set('expiry-key', 'this will last a very long time');

// Expire this key at 2222/02/22 02:22:22 GMT
$redis->expireAt('expiry-key', 7955144542);

var_dump($redis->expiretime('expiry-key'));

Parameters

string $key

The key to check.

Return Value

Redis|int|false

The timestamp when the key expires, or -1 if the key has no expiry and -2 if the key doesn't exist.

See also

https://redis.io/commands/expiretime

Redis|int|false pexpiretime(string $key)

Get the expriation timestamp of a given Redis key but in milliseconds.

Parameters

string $key

The key to check

Return Value

Redis|int|false

The expiration timestamp of this key (in milliseconds) or -1 if the key has no expiration, and -2 if it does not exist.

See also

https://redis.io/commands/pexpiretime
Redis::expiretime

Redis|bool flushAll(bool|null $sync = null)

Deletes every key in all Redis databases

Parameters

bool|null $sync

Whether to perform the task in a blocking or non-blocking way.

Return Value

Redis|bool

See also

https://redis.io/commands/flushall

Redis|bool flushDB(bool|null $sync = null)

Deletes all the keys of the currently selected database.

Parameters

bool|null $sync

Whether to perform the task in a blocking or non-blocking way.

Return Value

Redis|bool

See also

https://redis.io/commands/flush

Redis|int|false geoadd(string $key, float $lng, float $lat, string $member, mixed ...$other_triples_and_options)

No description

Parameters

string $key
float $lng
float $lat
string $member
mixed ...$other_triples_and_options

Return Value

Redis|int|false

Redis|float|false geodist(string $key, string $src, string $dst, string|null $unit = null)

No description

Parameters

string $key
string $src
string $dst
string|null $unit

Return Value

Redis|float|false

Redis|array|false geohash(string $key, string $member, string ...$other_members)

No description

Parameters

string $key
string $member
string ...$other_members

Return Value

Redis|array|false

Redis|array|false geopos(string $key, string $member, string ...$other_members)

No description

Parameters

string $key
string $member
string ...$other_members

Return Value

Redis|array|false

mixed georadius(string $key, float $lng, float $lat, float $radius, string $unit, array $options = [])

No description

Parameters

string $key
float $lng
float $lat
float $radius
string $unit
array $options

Return Value

mixed

mixed georadius_ro(string $key, float $lng, float $lat, float $radius, string $unit, array $options = [])

No description

Parameters

string $key
float $lng
float $lat
float $radius
string $unit
array $options

Return Value

mixed

mixed georadiusbymember(string $key, string $member, float $radius, string $unit, array $options = [])

No description

Parameters

string $key
string $member
float $radius
string $unit
array $options

Return Value

mixed

mixed georadiusbymember_ro(string $key, string $member, float $radius, string $unit, array $options = [])

No description

Parameters

string $key
string $member
float $radius
string $unit
array $options

Return Value

mixed

array geosearch(string $key, array|string $position, array|int|float $shape, string $unit, array $options = [])

No description

Parameters

string $key
array|string $position
array|int|float $shape
string $unit
array $options

Return Value

array

Redis|array|int|false geosearchstore(string $dst, string $src, array|string $position, array|int|float $shape, string $unit, array $options = [])

No description

Parameters

string $dst
string $src
array|string $position
array|int|float $shape
string $unit
array $options

Return Value

Redis|array|int|false

mixed get(string $key)

No description

Parameters

string $key

Return Value

mixed

mixed getAuth()

Get the authentication information on the connection, if any.

Return Value

mixed

The authentication information used to authenticate the connection.

See also

Redis::auth

Redis|int|false getBit(string $key, int $idx)

No description

Parameters

string $key
int $idx

Return Value

Redis|int|false

Redis|string|bool getEx(string $key, array $options = [])

No description

Parameters

string $key
array $options

Return Value

Redis|string|bool

int getDBNum()

Get the database number PhpRedis thinks we're connected to.

This value is updated internally in PhpRedis each time Redis::select is called.

Return Value

int

database we're connected to.

See also

Redis::select
https://redis.io/commands/select

Redis|string|bool getDel(string $key)

No description

Parameters

string $key

Return Value

Redis|string|bool

string getHost()

Return the host or Unix socket we are connected to.

Return Value

string

The host or Unix socket.

string|null getLastError()

Get the last error returned to us from Redis, if any.

Return Value

string|null

The error string or NULL if there is none.

int getMode()

Returns whether the connection is in ATOMIC, MULTI, or PIPELINE mode

Return Value

int

The mode we're in.

mixed getOption(int $option)

Retrieve the value of a configuration setting as set by Redis::setOption()

Parameters

int $option

Return Value

mixed

The setting itself or false on failure

See also

Redis::setOption for a detailed list of options and their values.

string|null getPersistentID()

Get the persistent connection ID, if there is one.

Return Value

string|null

The ID or NULL if we don't have one.

int getPort()

Get the port we are connected to. This number will be zero if we are connected to a unix socket.

Return Value

int

The port.

Redis|string|false getRange(string $key, int $start, int $end)

Retrieve a substring of a string by index.

$redis = new Redis(['host' => 'localhost']);

$word = 'Supercalifragilisticexpialidocious';
$redis->set('silly-word', $word);

// string "super"
var_dump($redis->getRange('silly-word', 0, 4));

// string(7) "docious"
var_dump($redis->getRange('silly-word', -7, -1));

Parameters

string $key

The string to query.

int $start

The zero-based starting index.

int $end

The zero-based ending index.

Return Value

Redis|string|false

The substring or false on failure.

See also

https://redis.io/commands/getrange

Redis|string|array|int|false lcs(string $key1, string $key2, array|null $options = NULL)

Get the longest common subsequence between two string keys.

$redis = new Redis(['host' => 'localhost']);

$redis->set('seq1', 'gtaggcccgcacggtctttaatgtatccctgtttaccatgccatacctgagcgcatacgc');
$redis->set('seq2', 'aactcggcgcgagtaccaggccaaggtcgttccagagcaaagactcgtgccccgctgagc');

// string(37) "acccgcacggcaagtcgttccagcaactggcgctagc"
var_dump($redis->lcs('seq1', 'seq2'));

Parameters

string $key1

The first key to check

string $key2

The second key to check

array|null $options

An optional array of modifiers for the comand.

$options = [
    'MINMATCHLEN'  => int  // Exclude matching substrings that are less than this value

    'WITHMATCHLEN' => bool // Whether each match should also include its length.

    'LEN'                  // Return the length of the longest subsequence

    'IDX'                  // Each returned match will include the indexes where the
                           // match occurs in each string.
];

NOTE: 'LEN' cannot be used with 'IDX'.

Return Value

Redis|string|array|int|false

Various reply types depending on options.

See also

https://redis.io/commands/lcs

float getReadTimeout()

Get the currently set read timeout on the connection.

Return Value

float

The timeout.

Redis|string|false getset(string $key, mixed $value)

Sets a key and returns any previously set value, if the key already existed.

$redis = new Redis(['host' => 'localhost']);

$redis->del('captain');

// bool(false)
var_dump($redis->getset('captain', 'Pike'));

// string(4) "Pike"
var_dump($redis->getset('captain', 'Kirk'));

Parameters

string $key

The key to set.

mixed $value

The value to set the key to.

Return Value

Redis|string|false

The old value of the key or false if it didn't exist.

See also

https://redis.io/commands/getset

float|false getTimeout()

Retrieve any set connection timeout

Return Value

float|false

The currently set timeout or false on failure (e.g. we aren't connected).

int|false getTransferredBytes()

No description

Return Value

int|false

Redis|int|false hDel(string $key, string $field, string ...$other_fields)

Remove one or more fields from a hash.

$redis = new Redis(['host' => 'localhost']);

$redis->del('people');

$redis->hmset('comms', ['Alice' => 'ecc', 'Bob' => 'rsa', 'Mallory' => 'haxx00r']);

// int(1)
$redis->hDel('comms', 'Mallory', 'Archibald');

Parameters

string $key

The hash key in question.

string $field

The first field to remove

string ...$other_fields

One or more additional fields to remove.

Return Value

Redis|int|false

The number of fields actually removed.

See also

https://redis.io/commands/hdel

Redis|bool hExists(string $key, string $field)

Checks whether a field exists in a hash.

$redis = new Redis(['host' => 'localhost']);

$redis->del('captains');

$redis->hmset('captains', ['Kirk' => 'Enterprise', 'Picard' => 'Enterprise-D', 'Sisko' => 'Defiant']);

$redis->hExists('captains', 'Pike');
$redis->hExists('captains', 'Picard');

Parameters

string $key

The hash to query.

string $field

The field to check

Return Value

Redis|bool

True if it exists, false if not.

See also

https://redis.io/commands/hexists

mixed hGet(string $key, string $member)

No description

Parameters

string $key
string $member

Return Value

mixed

Redis|array|false hGetAll(string $key)

Read every field and value from a hash.

$redis = new Redis(['host' => 'localhost']);

$redis->del('comms');

$redis->hmset('comms', ['Alice' => 'ecc', 'Bob' => 'rsa', 'Mallory' => 'haxx00r']);

// array(3) {
//   ["Alice"]=>
//   string(3) "ecc"
//   ["Bob"]=>
//   string(3) "rsa"
//   ["Mallory"]=>
//   string(7) "haxx00r"
// }
$redis->hGetAll('comms');

Parameters

string $key

The hash to query.

Return Value

Redis|array|false

All fields and values or false if the key didn't exist.

See also

https://redis.io/commands/hgetall

Redis|int|false hIncrBy(string $key, string $field, int $value)

Increment a hash field's value by an integer

$redis = new Redis(['host' => 'localhost']);

$redis->del('player');

$redis->hmset('player', ['name' => 'Bob', 'level' => 1]);

// int(2)
$redis->hIncrBy('player', 'level', 1);

// int(5)
$redis->hIncrBy('player', 'level', 3);

Parameters

string $key

The hash to modify

string $field

The field to increment

int $value

How much to increment the value.

Return Value

Redis|int|false

The new value of the field.

See also

https://redis.io/commands/hincrby

Redis|float|false hIncrByFloat(string $key, string $field, float $value)

Increment a hash field by a floating point value

$redis = new Redis(['host' => 'localhost']);

$redis->del('trig-numbers')

// float(3.1415926)
$pi = $redis->hIncrByFloat('trig-numbers', 'pi', 3.1415926);

// float(6.2831852)
$redis->hIncrByFloat('trig-numbers', 'tau', 2 * $pi);

Parameters

string $key

The hash with the field to increment.

string $field

The field to increment.

float $value

Return Value

Redis|float|false

The field value after incremented.

See also

https://redis.io/commands/hincrbyfloat

Redis|array|false hKeys(string $key)

Retrieve all of the fields of a hash.

$redis = new Redis(['host' => 'localhost']);

$redis->del('ships');

$redis->hmset('ships', ['Enterprise' => 'NCC-1701D', 'Defiant' => 'NX-74205', 'Voyager' => 'NCC-74656']);

// array(3) {
//   [0]=>
//   string(10) "Enterprise"
//   [1]=>
//   string(7) "Defiant"
//   [2]=>
//   string(7) "Voyager"
// }
$redis->hKeys('ships');

Parameters

string $key

The hash to query.

Return Value

Redis|array|false

The fields in the hash or false if the hash doesn't exist.

See also

https://redis.io/commands/hkeys

Redis|int|false hLen(string $key)

Get the number of fields in a hash.

Parameters

string $key

The hash to check.

Return Value

Redis|int|false

The number of fields or false if the key didn't exist.

See also

https://redis.io/commands/hlen

Redis|array|false hMget(string $key, array $fields)

Get one or more fields from a hash.

$redis = new Redis(['host' => 'localhost']);

$redis->del('player:1');

$redis->hmset('player:1', ['name' => 'Alice', 'age' => '26', 'score' => '1337']);

// array(2) {
//   ["name"]=>
//   string(5) "Alice"
//   ["score"]=>
//   string(4) "1337"
// }
$redis->hmget('player:1', ['name', 'score']);

Parameters

string $key

The hash to query.

array $fields

One or more fields to query in the hash.

Return Value

Redis|array|false

The fields and values or false if the key didn't exist.

See also

https://redis.io/commands/hmget

Redis|bool hMset(string $key, array $fieldvals)

Add or update one or more hash fields and values

$redis = new Redis(['host' => 'localhost']);

$redis->hmset('updates', ['status' => 'starting', 'elapsed' => 0]);

Parameters

string $key

The hash to create/update

array $fieldvals

An associative array with fields and their values.

Return Value

Redis|bool

True if the operation was successful

See also

https://redis.io/commands/hmset

Redis|string|array hRandField(string $key, array $options = null)

Get one or more random field from a hash.

$redis = new Redis(['host' => 'localhost']);

$redis->del('settings');

$redis->hmset('settings', ['path' => '/', 'state' => 'active', 'jobs' => 15]);

$redis->hrandfield('settings');
$redis->hrandfield('settings', ['count' => 2, 'withvalues' => true]);

Parameters

string $key

The hash to query.

array $options

An array of options to modify how the command behaves.

$options = [
    'COUNT'      => int  // An optional number of fields to return.
    'WITHVALUES' => bool // Also return the field values.
];

Return Value

Redis|string|array

One or more random fields (and possibly values).

See also

https://redis.io/commands/hrandfield

Redis|int|false hSet(string $key, string $member, mixed $value)

No description

Parameters

string $key
string $member
mixed $value

Return Value

Redis|int|false

Redis|bool hSetNx(string $key, string $field, string $value)

Set a hash field and value, but only if that field does not exist

$redis = new Redis(['host' => 'localhost']);

$redis->del('player:1');

$redis->hmset('player:1', ['name' => 'bob', 'score' => 0]);

// bool(true)
var_dump($redis->hsetnx('player:1', 'lock', 'enabled'));

// bool(false)
var_dump($redis->hsetnx('player:1', 'lock', 'enabled'));

Parameters

string $key

The hash to update.

string $field

The value to set.

string $value

Return Value

Redis|bool

True if the field was set and false if not.

See also

https://redis.io/commands/hsetnx

Redis|int|false hStrLen(string $key, string $field)

Get the string length of a hash field

Parameters

string $key

The hash to query.

string $field

The field to query.

Return Value

Redis|int|false

The string length of the field or false.

See also

https://redis.io/commands/hstrlen

Examples

$redis = new Redis(['host' => 'localhost']);
$redis->del('hash');
$redis->hmset('hash', ['50bytes' => str_repeat('a', 50)]);
$redis->hstrlen('hash', '50bytes');

Redis|array|false hVals(string $key)

Get all of the values from a hash.

Parameters

string $key

The hash to query.

Return Value

Redis|array|false

The values from the hash.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('player');

$redis->hmset('player', ['name' => 'Alice', 'score' => 1337]);

// array(2) {
//   ["name"]=>
//   string(5) "Alice"
//   ["score"]=>
//   string(4) "1337"
// }
$redis->hgetall('player');
?>

See also

https://redis.io/commands/hvals

Redis|array|bool hscan(string $key, int|null $iterator, string|null $pattern = null, int $count = 0)

Iterate over the fields and values of a hash in an incremental fashion.

Parameters

string $key

The hash to query.

int|null $iterator

The scan iterator, which should be initialized to NULL before the first call. This value will be updated after every call to hscan, until it reaches zero meaning the scan is complete.

string|null $pattern

An optional glob-style pattern to filter fields with.

int $count

An optional hint to Redis about how many fields and values to return per HSCAN.

Return Value

Redis|array|bool

An array with a subset of fields and values.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('big-hash');

for ($i = 0; $i < 1000; $i++) {
    $fields["field:$i"] = "value:$i";
}

$redis->hmset('big-hash', $fields);

$it = NULL;

do {
    // Scan the hash but limit it to fields that match '*:1?3'
    $fields = $redis->hscan('big-hash', $it, '*:1?3');

    foreach ($fields as $field => $value) {
        echo "[$field] => $value\n";
    }
} while ($it != 0);

// --- OUTPUT ---
// [field:143] => value:143
// [field:133] => value:133
// [field:163] => value:163
// [field:183] => value:183
// [field:153] => value:153
// [field:113] => value:113
// [field:103] => value:103
// [field:193] => value:193
// [field:123] => value:123
// [field:173] => value:173
?>

See also

https://redis.io/commands/hscan
https://redis.io/commands/scan

Redis|int|false incr(string $key, int $by = 1)

Increment a key's value, optionally by a specifc amount.

Parameters

string $key

The key to increment

int $by

An optional amount to increment by.

Return Value

Redis|int|false

The new value of the key after incremented.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->set('counter', 1);

// int(2);
$redis->incr('counter');

// int(4);
$redis->incr('counter', 2);
?>

See also

https://redis.io/commands/incr
https://redis.io/commands/incrby

Redis|int|false incrBy(string $key, int $value)

Increment a key by a specific integer value

Parameters

string $key

The key to increment.

int $value

The amount to increment.

<?php

$redis = new Redis(['host' => 'localhost']);

$redis->set('primes', 2);

// int(3)
$redis->incrby('primes', 1);

// int(5)
$redis->incrby('primes', 2);

// int(7)
$redis->incrby('primes', 2);

// int(11)
$redis->incrby('primes', 4);
?>

Return Value

Redis|int|false

See also

https://redis.io/commands/incrby

Redis|float|false incrByFloat(string $key, float $value)

Increment a numeric key by a floating point value.

Parameters

string $key

The key to increment

float $value

How much to increment (or decrement) the value.

Return Value

Redis|float|false

The new value of the key or false if the key didn't contain a string.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('tau');

// float(3.1415926)
var_dump($redis->incrByFloat('tau', 3.1415926));

// float(6.2831852)
var_dump($redis->incrByFloat('tau', 3.1415926));
?>

Redis|array|false info(string ...$sections)

Retrieve information about the connected redis-server. If no arguments are passed to this function, redis will return every info field. Alternatively you may pass a specific section you want returned (e.g. 'server', or 'memory') to receive only information pertaining to that section.

If connected to Redis server >= 7.0.0 you may pass multiple optional sections.

Parameters

string ...$sections

Optional section(s) you wish Redis server to return.

Return Value

Redis|array|false

See also

https://redis.io/commands/info/

bool isConnected()

Check if we are currently connected to a Redis instance.

Return Value

bool

True if we are, false if not

Redis|array|false keys(string $pattern)

No description

Parameters

string $pattern

Return Value

Redis|array|false

Redis|int|false lInsert(string $key, string $pos, mixed $pivot, mixed $value)

No description

Parameters

string $key
string $pos
mixed $pivot
mixed $value

Return Value

Redis|int|false

Redis|int|false lLen(string $key)

No description

Parameters

string $key

Return Value

Redis|int|false

Redis|string|false lMove(string $src, string $dst, string $wherefrom, string $whereto)

No description

Parameters

string $src
string $dst
string $wherefrom
string $whereto

Return Value

Redis|string|false

Redis|bool|string|array lPop(string $key, int $count = 0)

No description

Parameters

string $key
int $count

Return Value

Redis|bool|string|array

Redis|null|bool|int|array lPos(string $key, mixed $value, array $options = null)

No description

Parameters

string $key
mixed $value
array $options

Return Value

Redis|null|bool|int|array

int|Redis lPush(string $key, mixed ...$elements)

No description

Parameters

string $key
mixed ...$elements

Return Value

int|Redis

Redis|int|false rPush(string $key, mixed ...$elements)

No description

Parameters

string $key
mixed ...$elements

Return Value

Redis|int|false

Redis|int|false lPushx(string $key, mixed $value)

No description

Parameters

string $key
mixed $value

Return Value

Redis|int|false

Redis|int|false rPushx(string $key, mixed $value)

No description

Parameters

string $key
mixed $value

Return Value

Redis|int|false

Redis|bool lSet(string $key, int $index, mixed $value)

No description

Parameters

string $key
int $index
mixed $value

Return Value

Redis|bool

int lastSave()

No description

Return Value

int

mixed lindex(string $key, int $index)

No description

Parameters

string $key
int $index

Return Value

mixed

Redis|array|false lrange(string $key, int $start, int $end)

No description

Parameters

string $key
int $start
int $end

Return Value

Redis|array|false

int|Redis|false lrem(string $key, mixed $value, int $count = 0)

No description

Parameters

string $key
mixed $value
int $count

Return Value

int|Redis|false

Redis|bool ltrim(string $key, int $start, int $end)

No description

Parameters

string $key
int $start
int $end

Return Value

Redis|bool

array|Redis mget(array $keys)

No description

Parameters

array $keys

Return Value

array|Redis

Redis|bool migrate(string $host, int $port, string|array $key, int $dstdb, int $timeout, bool $copy = false, bool $replace = false, mixed $credentials = NULL)

No description

Parameters

string $host
int $port
string|array $key
int $dstdb
int $timeout
bool $copy
bool $replace
mixed $credentials

Return Value

Redis|bool

bool move(string $key, int $index)

No description

Parameters

string $key
int $index

Return Value

bool

Redis|bool mset(array $key_values)

No description

Parameters

array $key_values

Return Value

Redis|bool

Redis|bool msetnx(array $key_values)

No description

Parameters

array $key_values

Return Value

Redis|bool

bool|Redis multi(int $value = Redis::MULTI)

No description

Parameters

int $value

Return Value

bool|Redis

Redis|int|string|false object(string $subcommand, string $key)

No description

Parameters

string $subcommand
string $key

Return Value

Redis|int|string|false

bool open(string $host, int $port = 6379, float $timeout = 0, string $persistent_id = NULL, int $retry_interval = 0, float $read_timeout = 0, array $context = NULL) deprecated

deprecated

No description

Parameters

string $host
int $port
float $timeout
string $persistent_id
int $retry_interval
float $read_timeout
array $context

Return Value

bool

bool pconnect(string $host, int $port = 6379, float $timeout = 0, string $persistent_id = NULL, int $retry_interval = 0, float $read_timeout = 0, array $context = NULL)

No description

Parameters

string $host
int $port
float $timeout
string $persistent_id
int $retry_interval
float $read_timeout
array $context

Return Value

bool

bool persist(string $key)

No description

Parameters

string $key

Return Value

bool

bool pexpire(string $key, int $timeout, string|null $mode = NULL)

Sets an expiration in milliseconds on a given key. If connected to Redis >= 7.0.0 you can pass an optional mode argument that modifies how the command will execute.

Redis::expire() for a description of the mode argument.

Parameters

string $key

The key to set an expiration on. @param string $mode A two character modifier that changes how the command works.

@return Redis|bool True if an expiry was set on the key, and false otherwise.

int $timeout
string|null $mode

Return Value

bool

Redis|bool pexpireAt(string $key, int $timestamp, string|null $mode = NULL)

Set a key's expiration to a specific Unix Timestamp in milliseconds. If connected to Redis >= 7.0.0 you can pass an optional 'mode' argument.

Parameters

string $key
int $timestamp
string|null $mode

Return Value

Redis|bool

See also

Redis::expire For a description of the mode argument. @param string $key The key to set an expiration on. @param string $mode A two character modifier that changes how the command works. @return Redis|bool True if an expiration was set on the key, false otherwise.

Redis|int pfadd(string $key, array $elements)

Add one or more elements to a Redis HyperLogLog key

Parameters

string $key

The key in question.

array $elements

One or more elements to add.

Return Value

Redis|int

Returns 1 if the set was altered, and zero if not.

See also

https://redis.io/commands/pfadd

Redis|int pfcount(string $key)

Retrieve the cardinality of a Redis HyperLogLog key.

Parameters

string $key

The key name we wish to query.

Return Value

Redis|int

The estimated cardinality of the set.

See also

https://redis.io/commands/pfcount

Redis|bool pfmerge(string $dst, array $srckeys)

Merge one or more source HyperLogLog sets into a destination set.

Parameters

string $dst

The destination key.

array $srckeys

One or more source keys.

Return Value

Redis|bool

Always returns true.

See also

https://redis.io/commands/pfmerge

Redis|string|bool ping(string $message = NULL)

PING the redis server with an optional string argument.

Parameters

string $message

An optional string message that Redis will reply with, if passed.

Return Value

Redis|string|bool

If passed no message, this command will simply return true. If a message is passed, it will return the message.

<?php
$redis = new Redis(['host' => 'localhost']);

// bool(true)
$redis->ping();

// string(9) "beep boop"
$redis->ping('beep boop');
?>

See also

https://redis.io/commands/ping

bool|Redis pipeline()

Enter into pipeline mode.

Pipeline mode is the highest performance way to send many commands to Redis as they are aggregated into one stream of commands and then all sent at once when the user calls Redis::exec().

NOTE: That this is shorthand for Redis::multi(Redis::PIPELINE)

Return Value

bool|Redis

The redis object is returned, to facilitate method chaining.

<?php
$redis = new Redis(['host' => 'localhost']);

// array(3) {
//   [0]=>
//   bool(true)
//   [1]=>
//   int(0)
//   [2]=>
//   int(3)
// }
$redis->pipeline()
      ->set('foo', 'bar')
      ->del('mylist')
      ->rpush('mylist', 'a', 'b', 'c')
      ->exec();
?>

bool popen(string $host, int $port = 6379, float $timeout = 0, string $persistent_id = NULL, int $retry_interval = 0, float $read_timeout = 0, array $context = NULL) deprecated

deprecated

No description

Parameters

string $host
int $port
float $timeout
string $persistent_id
int $retry_interval
float $read_timeout
array $context

Return Value

bool

bool|Redis psetex(string $key, int $expire, mixed $value)

No description

Parameters

string $key
int $expire
mixed $value

Return Value

bool|Redis

bool psubscribe(array $patterns, callable $cb)

Subscribe to one or more glob-style patterns

Parameters

array $patterns

One or more patterns to subscribe to.

callable $cb

A callback with the following prototype:

function ($redis, $channel, $message) { }

Return Value

bool

True if we were subscribed.

See also

https://redis.io/commands/psubscribe

Redis|int|false pttl(string $key)

Get a keys time to live in milliseconds.

Parameters

string $key

The key to check.

Return Value

Redis|int|false

The keys TTL or false on failure.

NOTE: -1 means a key has no TTL and -2 means the key doesn't exist.

<?php

$redis = new Redis(['host' => 'localhost']);

$redis->setex('ttl-key', 60, 'ttl-value');

// int(60000)
var_dump($redis->pttl('ttl-key'));
?>

See also

https://redis.io/commands/pttl

Redis|int|false publish(string $channel, string $message)

Publish a message to a pubsub channel

Parameters

string $channel

The channel to publish to.

string $message

The message itself.

Return Value

Redis|int|false

The number of subscribed clients to the given channel.

See also

https://redis.io/commands/publish

mixed pubsub(string $command, mixed $arg = null)

No description

Parameters

string $command
mixed $arg

Return Value

mixed

Redis|array|bool punsubscribe(array $patterns)

Unsubscribe from one or more channels by pattern

Parameters

array $patterns

One or more glob-style patterns of channel names.

Return Value

Redis|array|bool

The array of subscribed patterns or false on failure.

See also

https://redis.io/commands/punsubscribe
https://redis.io/commands/subscribe
Redis::subscribe

Redis|array|string|bool rPop(string $key, int $count = 0)

Pop one or more elements from the end of a list.

Parameters

string $key

A redis LIST key name.

int $count

The maximum number of elements to pop at once.

NOTE: The count argument requires Redis >= 6.2.0

Return Value

Redis|array|string|bool

One ore more popped elements or false if all were empty.

<?php
<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('mylist');
$redis->rPush('mylist', 'one', 'two', 'three');

// string(5) "three"
$redis->rPop('mylist');

// string(3) "two"
$redis->rPop('mylist');

// string(3) "one"
$redis->rPop('mylist');
?>

See also

https://redis.io/commands/rpop

Redis|string|false randomKey()

Return a random key from the current database

Return Value

Redis|string|false

A random key name or false if no keys exist

See also

https://redis.io/commands/randomkey

mixed rawcommand(string $command, mixed ...$args)

Execute any arbitrary Redis command by name.

Parameters

string $command

The command to execute

mixed ...$args

One or more arguments to pass to the command.

<?php

$redis = new Redis(['host' => 'localhost']);

$redis->rawCommand('del', 'mystring', 'mylist');
$redis->rawCommand('set', 'mystring', 'myvalue');
$redis->rawCommand('rpush', 'mylist', 'one', 'two', 'three');

// string(7) "myvalue"
$redis->rawCommand('get', 'mystring');

// array(3) {
//   [0]=>
//   string(3) "one"
//   [1]=>
//   string(3) "two"
//   [2]=>
//   string(5) "three"
// }
$redis->rawCommand('lrange', 'mylist', 0, -1);
?>

Return Value

mixed

Redis|bool rename(string $old_name, string $new_name)

Unconditionally rename a key from $old_name to $new_name

Parameters

string $old_name

The original name of the key

string $new_name

The new name for the key

Return Value

Redis|bool

True if the key was renamed or false if not.

See also

https://redis.io/commands/rename

Redis|bool renameNx(string $key_src, string $key_dst)

Renames $key_src to $key_dst but only if newkey does not exist.

Parameters

string $key_src

The source key name

string $key_dst

The destination key name.

Return Value

Redis|bool

True if the key was renamed, false if not.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('src', 'dst', 'existing-dst');

$redis->set('src', 'src_key');
$redis->set('existing-dst', 'i_exist');

// bool(true)
$redis->renamenx('src', 'dst');

// bool(false)
$redis->renamenx('dst', 'existing-dst');
?>

See also

https://redis.io/commands/renamenx

Redis|bool reset()

Reset the state of the connection.

Return Value

Redis|bool

Should always return true unless there is an error.

Redis|bool restore(string $key, int $ttl, string $value, array|null $options = NULL)

Restore a key by the binary payload generated by the DUMP command.

Parameters

string $key

The name of the key you wish to create.

int $ttl

What Redis should set the key's TTL (in milliseconds) to once it is created. Zero means no TTL at all.

string $value

The serialized binary value of the string (generated by DUMP).

array|null $options

An array of additional options that modifies how the command operates.

$options = [
    'ABSTTL'          // If this is present, the `$ttl` provided by the user should
                      // be an absolute timestamp, in milliseconds()

    'REPLACE'         // This flag instructs Redis to store the key even if a key with
                      // that name already exists.

    'IDLETIME' => int // Tells Redis to set the keys internal 'idletime' value to a
                      // specific number (see the Redis command OBJECT for more info).
    'FREQ'     => int // Tells Redis to set the keys internal 'FREQ' value to a specific
                      // number (this relates to Redis' LFU eviction algorithm).
];

Return Value

Redis|bool

True if the key was stored, false if not.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('captains');

$redis->sAdd('captains', 'Janeway', 'Picard', 'Sisko', 'Kirk', 'Archer');

$serialized = $redis->dump('captains');

$redis->select(1);
$redis->restore('captains-backup', 0, $serialized);

//array(5) {
//  [0]=>
//  string(6) "Archer"
//  [1]=>
//  string(4) "Kirk"
//  [2]=>
//  string(5) "Sisko"
//  [3]=>
//  string(6) "Picard"
//  [4]=>
//  string(7) "Janeway"
//}
var_dump($redis->sMembers('captains-backup'));
?>

See also

https://redis.io/commands/restore
https://redis.io/commands/dump
Redis::dump

mixed role()

Query whether the connected instance is a primary or replica

Return Value

mixed

Will return an array with the role of the connected instance unless there is an error.

Redis|string|false rpoplpush(string $srckey, string $dstkey)

Atomically pop an element off the end of a Redis LIST and push it to the beginning of another.

Parameters

string $srckey

The source key to pop from.

string $dstkey

The destination key to push to.

Return Value

Redis|string|false

The popped element or false if the source key was empty.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->pipeline()
      ->del('list1', 'list2')
      ->rpush('list1', 'list1-1', 'list1-2')
      ->rpush('list2', 'list2-1', 'list2-2')
      ->exec();

var_dump($redis->rpoplpush('list2', 'list1'));
var_dump($redis->lrange('list1', 0, -1));

// --- OUTPUT ---
// string(7) "list2-2"
//
// array(3) {
//   [0]=>
//   string(7) "list2-2"
//   [1]=>
//   string(7) "list1-1"
//   [2]=>
//   string(7) "list1-2"
// }
?>

See also

https://redis.io/commands/rpoplpush

Redis|int|false sAdd(string $key, mixed $value, mixed ...$other_values)

Add one or more values to a Redis SET key.

Parameters

string $key

The key name

mixed $value
mixed ...$other_values

Return Value

Redis|int|false

The number of values added to the set.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('myset');

var_dump($redis->sadd('myset', 'foo', 'bar', 'baz'));
var_dump($redis->sadd('myset', 'foo', 'new'));

// --- OUTPUT ---
// int(3)
// int(1)
?>

See also

https://redis.io/commands/sadd

int sAddArray(string $key, array $values)

Add one ore more values to a Redis SET key. This is an alternative to Redis::sadd() but instead of being variadic, takes a single array of values.

Parameters

string $key

The set to add values to.

array $values

One or more members to add to the set.

Return Value

int

The number of members added to the set.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('myset');

var_dump($redis->sAddArray('myset', ['foo', 'bar', 'baz']));
var_dump($redis->sAddArray('myset', ['foo', 'new']));

// --- OUTPUT ---
// int(3)
// int(1)
?>

See also

https://redis.io/commands/sadd
\Redis::sadd()

Redis|array|false sDiff(string $key, string ...$other_keys)

Given one or more Redis SETS, this command returns all of the members from the first set that are not in any subsequent set.

Parameters

string $key

The first set

string ...$other_keys

One or more additional sets

Return Value

Redis|array|false

Returns the elements from keys 2..N that don't exist in the first sorted set, or false on failure.


<?php
$redis = new Redis(['host' => 'localhost']);

$redis->pipeline()
      ->del('set1', 'set2', 'set3')
      ->sadd('set1', 'apple', 'banana', 'carrot', 'date')
      ->sadd('set2', 'carrot')
      ->sadd('set3', 'apple', 'carrot', 'eggplant')
      ->exec();

// NOTE:  'banana' and 'date' are in set1 but none of the subsequent sets.
var_dump($redis->sdiff('set1', 'set2', 'set3'));

// --- OUTPUT ---
array(2) {
  [0]=>
  string(6) "banana"
  [1]=>
  string(4) "date"
}
?>

See also

https://redis.io/commands/sdiff

Redis|int|false sDiffStore(string $dst, string $key, string ...$other_keys)

This method performs the same operation as SDIFF except it stores the resulting diff values in a specified destination key.

Parameters

string $dst

The key where to store the result

string $key

The first key to perform the DIFF on

string ...$other_keys

One or more additional keys.

Return Value

Redis|int|false

The number of values stored in the destination set or false on failure.

See also

https://redis.io/commands/sdiffstore
\Redis::sdiff()

Redis|array|false sInter(array|string $key, string ...$other_keys)

Given one or more Redis SET keys, this command will return all of the elements that are in every one.

Parameters

array|string $key

The first SET key to intersect.

string ...$other_keys

One or more Redis SET keys.

<?php

$redis = new Redis(['host' => 'localhost']);

$redis->pipeline()
      ->del('alice_likes', 'bob_likes', 'bill_likes')
      ->sadd('alice_likes', 'asparagus', 'broccoli', 'carrot', 'potato')
      ->sadd('bob_likes', 'asparagus', 'carrot', 'potato')
      ->sadd('bill_likes', 'broccoli', 'potato')
      ->exec();

// NOTE:  'potato' is the only value in all three sets
var_dump($redis->sinter('alice_likes', 'bob_likes', 'bill_likes'));

// --- OUTPUT ---
// array(1) {
//   [0]=>
//   string(6) "potato"
// }
?>

Return Value

Redis|array|false

See also

https://redis.io/commands/sinter

Redis|int|false sintercard(array $keys, int $limit = -1)

Compute the intersection of one or more sets and return the cardinality of the result.

Parameters

array $keys

One or more set key names.

int $limit

A maximum cardinality to return. This is useful to put an upper bound on the amount of work Redis will do.

Return Value

Redis|int|false

The

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('set1', 'set2', 'set3');

$redis->sAdd('set1', 'apple', 'pear', 'banana', 'carrot');
$redis->sAdd('set2', 'apple',         'banana');
$redis->sAdd('set3',          'pear', 'banana');

// int(1)
var_dump($redis->sInterCard(['set1', 'set2', 'set3']));
?>

See also

https://redis.io/commands/sintercard

Redis|int|false sInterStore(array|string $key, string ...$other_keys)

Perform the intersection of one or more Redis SETs, storing the result in a destination key, rather than returning them.

Parameters

array|string $key
string ...$other_keys

If the first argument was a string, subsequent arguments should be source key names.

Return Value

Redis|int|false

The number of values stored in the destination key or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

// OPTION 1:  A single array
$redis->sInterStore(['dst', 'src1', 'src2', 'src3']);

// OPTION 2:  Variadic
$redis->sInterStore('dst', 'src1', 'src'2', 'src3');
?>

See also

https://redis.io/commands/sinterstore
\Redis::sinter()

Redis|array|false sMembers(string $key)

Retrieve every member from a set key.

Parameters

string $key

The set name.

Return Value

Redis|array|false

Every element in the set or false on failure.

$redis = new Redis(['host' => 'localhost']);

$redis->del('tng-crew');

$redis->sAdd('tng-crew', ...['Picard', 'Riker', 'Data', 'Worf', 'La Forge', 'Troi', 'Crusher', 'Broccoli']);

// Array
// (
//     [0] => Riker
//     [1] => Crusher
//     [2] => Troi
//     [3] => Worf
//     [4] => LaForge
//     [5] => Picard
//     [6] => Broccoli
//     [7] => Data
// )
$redis->sMembers('tng-crew');

See also

https://redis.io/commands/smembers

Redis|array|false sMisMember(string $key, string $member, string ...$other_members)

Check if one or more values are members of a set.

Parameters

string $key

The set to query.

string $member

The first value to test if exists in the set.

string ...$other_members

Any number of additional values to check.

Return Value

Redis|array|false

An array of integers representing whether each passed value was a member of the set.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('ds9-crew');
$redis->sAdd('ds9-crew', ...["Sisko", "Kira", "Dax", "Worf", "Bashir", "O'Brien"]);

$names = ['Sisko', 'Picard', 'Data', 'Worf'];
$members = $redis->sMIsMember('ds9-crew', ...$names);

// array(4) {
//   ["Sisko"]=>
//   int(1)
//   ["Picard"]=>
//   int(0)
//   ["Data"]=>
//   int(0)
//   ["Worf"]=>
//   int(1)
// }
var_dump(array_combine($names, $members));
?>

See also

https://redis.io/commands/smismember
https://redis.io/commands/smember
\Redis::smember()

Redis|bool sMove(string $src, string $dst, mixed $value)

Pop a member from one set and push it onto another. This command will create the destination set if it does not currently exist.

Parameters

string $src

The source set.

string $dst

The destination set.

mixed $value

The member you wish to move.

Return Value

Redis|bool

True if the member was moved, and false if it wasn't in the set.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('numbers', 'evens');
$redis->sAdd('numbers', 'zero', 'one', 'two', 'three', 'four');

$redis->sMove('numbers', 'evens', 'zero');
$redis->sMove('numbers', 'evens', 'two');
$redis->sMove('numbers', 'evens', 'four');

// array(2) {
//   [0]=>
//   string(5) "three"
//   [1]=>
//   string(3) "one"
// }
var_dump($redis->sMembers('numbers'));

// array(3) {
//   [0]=>
//   string(4) "zero"
//   [1]=>
//   string(3) "two"
//   [2]=>
//   string(4) "four"
// }
var_dump($redis->sMembers('evens'));

?>

See also

https://redis.io/commands/smove

Redis|string|array|false sPop(string $key, int $count = 0)

Remove one or more elements from a set.

Parameters

string $key

The set in question.

int $count

An optional number of members to pop. This defaults to removing one element.

<?php
$redis = new Redis(['host' => 'localhost']);

<?php

$redis = new Redis(['host' => 'localhost']);

$redis->del('numbers', 'evens');
$redis->sAdd('numbers', 'zero', 'one', 'two', 'three', 'four');

$redis->sMove('numbers', 'evens', 'zero');
$redis->sMove('numbers', 'evens', 'two');
$redis->sMove('numbers', 'evens', 'four');

// array(2) {
//   [0]=>
//   string(5) "three"
//   [1]=>
//   string(3) "one"
// }
var_dump($redis->sMembers('numbers'));

// array(3) {
//   [0]=>
//   string(4) "zero"
//   [1]=>
//   string(3) "two"
//   [2]=>
//   string(4) "four"
// }
var_dump($redis->sMembers('evens'));
?>

Return Value

Redis|string|array|false

See also

https://redis.io/commands/spop

Redis|string|array|false sRandMember(string $key, int $count = 0)

Retrieve one or more random members of a set.

Parameters

string $key

The set to query.

int $count

An optional count of members to return.

If this value is positive, Redis will return up to the requested number but with unique elements that will never repeat. This means you may recieve fewer then $count replies.

If the number is negative, Redis will return the exact number requested but the result may contain duplicate elements.

Return Value

Redis|string|array|false

One or more random members or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('elder-gods');

$redis->sAdd('elder-gods', ["Cthulhu", "Azathoth", "Daoloth", "D'endrrah"]);

// A single random member returned.
$rng1 = $redis->sRandMember('elder-gods');

// Up to SCARD `elder-gods` random members returned
$rng2 = $redis->sRandMember('elder-gods', 9999);

// 9999 elements from the set returned with duplicates
$rng3 = $redis->sRandMember('elder-gods', -9999);
?>

Redis|array|false sUnion(string $key, string ...$other_keys)

Returns the union of one or more Redis SET keys.

Parameters

string $key

The first SET to do a union with

string ...$other_keys

One or more subsequent keys

Return Value

Redis|array|false

The union of the one or more input sets or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->pipeline()
      ->del('set1', 'set2', 'set3')
      ->sadd('set1', 'apple', 'banana', 'carrot')
      ->sadd('set2', 'apple', 'carrot', 'fish')
      ->sadd('set3', 'carrot', 'fig', 'eggplant');

var_dump($redis->sunion('set1', 'set2', 'set3'));

// --- OPUTPUT ---
// array(5) {
//   [0]=>
//   string(6) "banana"
//   [1]=>
//   string(5) "apple"
//   [2]=>
//   string(4) "fish"
//   [3]=>
//   string(6) "carrot"
//   [4]=>
//   string(8) "eggplant"
// }
?>

See also

https://redis.io/commands/sunion

Redis|int|false sUnionStore(string $dst, string $key, string ...$other_keys)

Perform a union of one or more Redis SET keys and store the result in a new set

Parameters

string $dst

The destination key

string $key

The first source key

string ...$other_keys

One or more additional source keys

Return Value

Redis|int|false

The number of elements stored in the destination SET or false on failure.

See also

https://redis.io/commands/sunionstore
\Redis::sunion()

Redis|bool save()

Persist the Redis database to disk. This command will block the server until the save is completed. For a nonblocking alternative, see Redis::bgsave().

Return Value

Redis|bool

Returns true unless an error occurs.

See also

https://redis.io/commands/save
\Redis::bgsave()

array|false scan(int|null $iterator, string|null $pattern = null, int $count = 0, string $type = NULL)

Incrementally scan the Redis keyspace, with optional pattern and type matching.

A note about Redis::SCAN_NORETRY and Redis::SCAN_RETRY.

For convenience, PhpRedis can retry SCAN commands itself when Redis returns an empty array of keys with a nonzero iterator. This can happen when matching against a pattern that very few keys match inside a key space with a great many keys. The following example demonstrates how to use Redis::scan() with the option disabled and enabled.

<?php

$redis = new Redis(['host' => 'localhost']);

$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NORETRY);

$it = NULL;

do {
    $keys = $redis->scan($it, '*zorg*');
    foreach ($keys as $key) {
        echo "KEY: $key\n";
    }
} while ($it != 0);

$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);

$it = NULL;

// When Redis::SCAN_RETRY is enabled, we can use simpler logic, as we will never receive an
// empty array of keys when the iterator is nonzero.
while ($keys = $redis->scan($it, '*zorg*')) {
    foreach ($keys as $key) {
        echo "KEY: $key\n";
    }
}
?>

Parameters

int|null $iterator

The cursor returned by Redis for every subsequent call to SCAN. On the initial invocation of the call, it should be initialized by the caller to NULL. Each time SCAN is invoked, the iterator will be updated to a new number, until finally Redis will set the value to zero, indicating that the scan is complete.

string|null $pattern

An optional glob-style pattern for matching key names. If passed as NULL, it is the equivalent of sending '*' (match every key).

int $count

A hint to redis that tells it how many keys to return in a single call to SCAN. The larger the number, the longer Redis may block clients while iterating the key space.

string $type

An optional argument to specify which key types to scan (e.g. 'STRING', 'LIST', 'SET')

Return Value

array|false

An array of keys, or false if no keys were returned for this invocation of scan. Note that it is possible for Redis to return zero keys before having scanned the entire key space, so the caller should instead continue to SCAN until the iterator reference is returned to zero.

See also

https://redis.io/commands/scan
Redis::setOption

Redis|int|false scard(string $key)

Retrieve the number of members in a Redis set.

Parameters

string $key

The set to get the cardinality of.

Return Value

Redis|int|false

The cardinality of the set or false on failure.

<?php

$redis = new Redis(['host' => 'localhost']);

$redis->del('set');
$redis->sadd('set', 'one', 'two', 'three', 'four', 'five');

// Returns 5
$redis->scard('set');
?>

See also

https://redis.io/commands/scard

mixed script(string $command, mixed ...$args)

An administrative command used to interact with LUA scripts stored on the server.

Parameters

string $command

The script suboperation to execute.

mixed ...$args

One ore more additional argument

Return Value

mixed

This command returns various things depending on the specific operation executed.

<?php
$redis = new Redis(['host' => 'localhost']);

$lua = sprintf("return %f", microtime(true));

// array(1) {
//   [0]=>
//   int(0)
// }
var_dump($redis->script('exists', sha1($lua)));

$redis->script('load', $lua);

// array(1) {
//   [0]=>
//   int(1)
// }
var_dump($redis->script('exists', sha1($lua)));
?>

See also

https://redis.io/commands/script

Redis|bool select(int $db)

Select a specific Redis database.

Parameters

int $db

The database to select. Note that by default Redis has 16 databases (0-15).

Return Value

Redis|bool

true on success and false on failure

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->select(1);
$redis->set('this_is_db_1', 'test');

$redis->select(0);
var_dump($redis->exists('this_is_db_1'));

$redis->select(1);
var_dump($redis->exists('this_is_db_1'));

// --- OUTPUT ---
// int(0)
// int(1)
?>

Redis|string|bool set(string $key, mixed $value, mixed $options = NULL)

Create or set a Redis STRING key to a value.

Parameters

string $key

The key name to set.

mixed $value

The value to set the key to.

mixed $options

Either an array with options for how to perform the set or an integer with an expiration. If an expiration is set PhpRedis will actually send the SETEX command.

OPTION DESCRIPTION


['EX' => 60] expire 60 seconds. ['PX' => 6000] expire in 6000 milliseconds. ['EXAT' => time() + 10] expire in 10 seconds. ['PXAT' => time()*1000 + 1000] expire in 1 second. ['KEEPTTL' => true] Redis will not update the key's current TTL. ['XX'] Only set the key if it already exists. ['NX'] Only set the key if it doesn't exist. ['GET'] Instead of returning +OK return the previous value of the key or NULL if the key didn't exist.

Return Value

Redis|string|bool

True if the key was set or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->set('key', 'value');

// Will actually send `SETEX 60 key value` to Redis.
$redis->set('key', 'expires_in_60_seconds', 60);

// Only have Redis set the key if it already exists.
$redis->set('key', 'options_set', ['XX']);

?>

See also

https://redis.io/commands/set
https://redis.io/commands/setex

Redis|int|false setBit(string $key, int $idx, bool $value)

Set a specific bit in a Redis string to zero or one

Parameters

string $key

The Redis STRING key to modify

int $idx
bool $value

Whether to set the bit to zero or one.

Return Value

Redis|int|false

The original value of the bit or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->set('foo', 'bar');

// Flip the 7th bit to 1
$redis->setbit('foo', 7, 1);

// The bit flip turned 'bar' -> 'car'
$redis->get('foo');
?>

See also

https://redis.io/commands/setbit

Redis|int|false setRange(string $key, int $index, string $value)

Update or append to a Redis string at a specific starting index

Parameters

string $key

The key to update

int $index

Where to insert the provided value

string $value

The value to copy into the string.

Return Value

Redis|int|false

The new length of the string or false on failure

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->set('message', 'Hello World');

// Update 'Hello World' to 'Hello Redis'
$redis->setRange('message', 6, 'Redis');
?>

See also

https://redis.io/commands/setrange

bool setOption(int $option, mixed $value)

Set a configurable option on the Redis object.

Following are a list of options you can set:

OPTION TYPE DESCRIPTION
OPT_MAX_RETRIES int The maximum number of times Redis will attempt to reconnect if it gets disconnected, before throwing an exception.
OPT_SCAN enum Redis::OPT_SCAN_RETRY, or Redis::OPT_SCAN_NORETRY. Whether PhpRedis should automatically SCAN again when zero keys but a nonzero iterator are returned.
OPT_SERIALIZER enum Set the automatic data serializer.
Redis::SERIALIZER_NONE
Redis::SERIALIZER_PHP
Redis::SERIALIZER_IGBINARY
Redis::SERIALIZER_MSGPACK, Redis::SERIALIZER_JSON
OPT_PREFIX string A string PhpRedis will use to prefix every key we read or write.
OPT_READ_TIMEOUT float How long PhpRedis will block for a response from Redis before throwing a 'read error on connection' exception.
OPT_TCP_KEEPALIVE bool Set or disable TCP_KEEPALIVE on the connection.
OPT_COMPRESSION enum Set the compression algorithm
Redis::COMPRESSION_NONE
Redis::COMPRESSION_LZF
Redis::COMPRESSION_LZ4
Redis::COMPRESSION_ZSTD
OPT_REPLY_LITERAL bool If set to true, PhpRedis will return the literal string Redis returns for LINE replies (e.g. '+OK'), rather than true.
OPT_COMPRESSION_LEVEL int Set a specific compression level if Redis is compressing data.
OPT_NULL_MULTIBULK_AS_NULL bool Causes PhpRedis to return NULL rather than false for NULL MULTIBULK replies
OPT_BACKOFF_ALGORITHM enum The exponential backoff strategy to use.
OPT_BACKOFF_BASE int The minimum delay between retries when backing off.
OPT_BACKOFF_CAP int The maximum delay between replies when backing off.

Parameters

int $option

The option constant.

mixed $value

The option value.

Return Value

bool

true if the setting was updated, false if not.

See also

Redis::getOption
Redis::__construct for details about backoff strategies.

Redis|bool setex(string $key, int $expire, mixed $value)

Set a Redis STRING key with a specific expiration in seconds.

Parameters

string $key

The name of the key to set.

int $expire

The key's expiration in seconds.

mixed $value

The value to set the key.

Return Value

Redis|bool

True on success or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

// Set a key with a 60 second expiration
$redis->set('some_key', 60, 'some_value');

?>php

Redis|bool setnx(string $key, mixed $value)

Set a key to a value, but only if that key does not already exist.

Parameters

string $key

The key name to set.

mixed $value

What to set the key to.

Return Value

Redis|bool

Returns true if the key was set and false otherwise.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('new-key');
$redis->set('existing-key', 'already-exists');

// Key is new, returns 1
$redis->setnx('key1', 'here-is-a-new-key');

// Key exists, returns 0
$redis->setnx('existing-key', 'new-value');
?>

See also

https://redis.io/commands/setnx

Redis|bool sismember(string $key, mixed $value)

Check whether a given value is the member of a Redis SET.

Parameters

string $key

The redis set to check.

mixed $value

The value to test.

Return Value

Redis|bool

True if the member exists and false if not.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->multi()
      ->del('myset')
      ->sadd('myset', 'foo', 'bar', 'baz')
      ->exec();

// Will return true, as 'foo' is in the set
$redis->sismember('myset', 'foo');

// Will return false, as 'not-in-set' is not in the set
$redis->sismember('myset', 'not-in-set');
?>

Redis|bool slaveof(string $host = NULL, int $port = 6379) deprecated

deprecated

Turn a redis instance into a replica of another or promote a replica to a primary.

This method and the corresponding command in Redis has been marked deprecated and users should instead use Redis::replicaof() if connecting to redis-server

= 5.0.0.

Parameters

string $host
int $port

Return Value

Redis|bool

See also

https://redis.io/commands/slaveof
https://redis.io/commands/replicaof
Redis::slaveof

Redis|bool replicaof(string $host = NULL, int $port = 6379)

Used to turn a Redis instance into a replica of another, or to remove replica status promoting the instance to a primary.

Parameters

string $host

The host of the primary to start replicating.

int $port

The port of the primary to start replicating.

Return Value

Redis|bool

Success if we were successfully able to start replicating a primary or were able to promote teh replicat to a primary.

<?php
$redis = new Redis(['host' => 'localhost']);

// Attempt to become a replica of a Redis instance at 127.0.0.1:9999
$redis->slaveof('127.0.0.1', 9999);

// When passed no arguments, PhpRedis will deliver the command `SLAVEOF NO ONE`
// attempting to promote the instance to a primary.
$redis->slaveof();
?>

See also

https://redis.io/commands/replicaof
https://redis.io/commands/slaveof
Redis::slaveof

Redis|int|false touch(array|string $key_or_array, string ...$more_keys)

Update one or more keys last modified metadata.

Parameters

array|string $key_or_array
string ...$more_keys

One or more keys to send to the command.

Return Value

Redis|int|false

This command returns the number of keys that exist and had their last modified time reset

See also

https://redis.io/commands/touch/

mixed slowlog(string $operation, int $length = 0)

Interact with Redis' slowlog functionality in various ways, depending on the value of 'operation'.

Parameters

string $operation

The operation you wish to perform.  This can be one of the following values: 'GET' - Retrieve the Redis slowlog as an array. 'LEN' - Retrieve the length of the slowlog. 'RESET' - Remove all slowlog entries.

<?php
$redis->slowlog('get', -1);  // Retrieve all slowlog entries.
$redis->slowlog('len');       // Retrieve slowlog length.
$redis->slowlog('reset');     // Reset the slowlog.
?>
int $length

This optional argument can be passed when operation is 'get' and will specify how many elements to retrieve. If omitted Redis will send up to a default number of entries, which is configurable.

Note: With Redis >= 7.0.0 you can send -1 to mean "all".

Return Value

mixed

See also

https://redis.io/commands/slowlog/

mixed sort(string $key, array|null $options = null)

Sort the contents of a Redis key in various ways.

Parameters

string $key

The key you wish to sort

array|null $options

Various options controlling how you would like the data sorted. See blow for a detailed description of this options array.

Return Value

mixed

This command can either return an array with the sorted data or the number of elements placed in a destination set when using the STORE option.

<?php
$options = [
    'SORT'  => 'ASC'|| 'DESC' // Sort in descending or descending order.
    'ALPHA' => true || false  // Whether to sort alphanumerically.
    'LIMIT' => [0, 10]        // Return a subset of the data at offset, count
    'BY'    => 'weight_*'     // For each element in the key, read data from the
                                 external key weight_* and sort based on that value.
    'GET'   => 'weight_*'     // For each element in the source key, retrieve the
                                 data from key weight_* and return that in the result
                                 rather than the source keys' element.  This can
                                 be used in combination with 'BY'
];
?>

See also

https://redis.io/commands/sort/

mixed sort_ro(string $key, array|null $options = null)

This is simply a read-only variant of the sort command

Parameters

string $key
array|null $options

Return Value

mixed

See also

Redis::sort

array sortAsc(string $key, string|null $pattern = null, mixed $get = null, int $offset = -1, int $count = -1, string|null $store = null) deprecated

deprecated

No description

Parameters

string $key
string|null $pattern
mixed $get
int $offset
int $count
string|null $store

Return Value

array

array sortAscAlpha(string $key, string|null $pattern = null, mixed $get = null, int $offset = -1, int $count = -1, string|null $store = null) deprecated

deprecated

No description

Parameters

string $key
string|null $pattern
mixed $get
int $offset
int $count
string|null $store

Return Value

array

array sortDesc(string $key, string|null $pattern = null, mixed $get = null, int $offset = -1, int $count = -1, string|null $store = null) deprecated

deprecated

No description

Parameters

string $key
string|null $pattern
mixed $get
int $offset
int $count
string|null $store

Return Value

array

array sortDescAlpha(string $key, string|null $pattern = null, mixed $get = null, int $offset = -1, int $count = -1, string|null $store = null) deprecated

deprecated

No description

Parameters

string $key
string|null $pattern
mixed $get
int $offset
int $count
string|null $store

Return Value

array

Redis|int|false srem(string $key, mixed $value, mixed ...$other_values)

Remove one or more values from a Redis SET key.

Parameters

string $key

The Redis SET key in question.

mixed $value

The first value to remove.

mixed ...$other_values

Return Value

Redis|int|false

The number of values removed from the set or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->pipeline()->del('set1')
                  ->sadd('set1', 'foo', 'bar', 'baz')
                  ->exec();

var_dump($redis->sRem('set1', 'foo', 'bar', 'not-in-the-set'));

// --- OUTPUT ---
// int(2)
?>

See also

https://redis.io/commands/srem

array|false sscan(string $key, int|null $iterator, string|null $pattern = null, int $count = 0)

Scan the members of a redis SET key.

Parameters

string $key

The Redis SET key in question.

int|null $iterator

A reference to an iterator which should be initialized to NULL that PhpRedis will update with the value returned from Redis after each subsequent call to SSCAN. Once this cursor is zero you know all members have been traversed.

string|null $pattern

An optional glob style pattern to match against, so Redis only returns the subset of members matching this pattern.

int $count

A hint to Redis as to how many members it should scan in one command before returning members for that iteration.

$redis = new Redis(['host' => 'localhost']);

$redis->del('myset');
for ($i = 0; $i < 10000; $i++) {
    $redis->sAdd('myset', "member:$i");
}
$redis->sadd('myset', 'foofoo');

$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NORETRY);

$scanned = 0;
$it = NULL;

// Without Redis::SCAN_RETRY we may receive empty results and
// a nonzero iterator.
do {
    // Scan members containing '5'
    $members = $redis->sscan('myset', $it, '*5*');
    foreach ($members as $member) {
         echo "NORETRY: $member\n";
         $scanned++;
    }
} while ($it != 0);
echo "TOTAL: $scanned\n";

$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);

$scanned = 0;
$it = NULL;

// With Redis::SCAN_RETRY PhpRedis will never return an empty array
// when the cursor is non-zero
while (($members = $redis->sscan('myset', $it, '*5*'))) {
    foreach ($members as $member) {
        echo "RETRY: $member\n";
        $scanned++;
    }
}
echo "TOTAL: $scanned\n";
?>

Return Value

array|false

See also

https://redis.io/commands/sscan
https://redis.io/commands/scan
Redis::setOption

Redis|int|false strlen(string $key)

Retrieve the length of a Redis STRING key.

Parameters

string $key

The key we want the length of.

Return Value

Redis|int|false

The length of the string key if it exists, zero if it does not, and false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('string');

$redis->set('string', 'foo');

// strlen('foo') == 3
$redis->strlen('string');

$redis->append('string', 'bar');

// strlen('foobar') == 6
$redis->strlen('string');

?>

bool subscribe(array $channels, callable $cb)

Subscribe to one or more Redis pubsub channels.

Parameters

array $channels

One or more channel names.

callable $cb

The callback PhpRedis will invoke when we receive a message from one of the subscribed channels.

Return Value

bool

True on success, false on faiilure. Note that this command will block the client in a subscribe loop, waiting for messages to arrive.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->subscribe(['channel-1', 'channel-2'], function ($redis, $channel, $message) {
    echo "[$channel]: $message\n";

    // Unsubscribe from the message channel when we read 'quit'
    if ($message == 'quit') {
        echo "Unsubscribing from '$channel'\n";
        $redis->unsubscribe([$channel]);
    }
});

// Once we read 'quit' from both channel-1 and channel-2 the subscribe loop will be
// broken and this command will execute.
echo "Subscribe loop ended\n";
?>

Redis|bool swapdb(int $src, int $dst)

Atomically swap two Redis databases so that all of the keys in the source database will now be in the destination database and vice-versa.

Note: This command simply swaps Redis' internal pointer to the database and is therefore very fast, regardless of the size of the underlying databases.

Parameters

int $src

The source database number

int $dst

The destination database number

Return Value

Redis|bool

Success if the databases could be swapped and false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->multi()->select(0)
               ->set('db0-key1', 'value1')->set('db0-key2', 'value2')
               ->select(1)
               ->set('db1-key1', 'value1')->set('db1-key2', 'value2')
               ->select(0)
               ->exec();

// Array
// (
//     [0] => db0-key1
//     [1] => db0-key2
// )
print_r($redis->keys('*'));

// Swap db0 and db1
$redis->swapdb(0, 1);

// Array
// (
//     [0] => db1-key2
//     [1] => db1-key1
// )
print_r($redis->keys('*'));

// Swap them back
$redis->swapdb(0, 1);

// Array
// (
//     [0] => db0-key1
//     [1] => db0-key2
// )
print_r($redis->keys('*'));
?>

See also

https://redis.io/commands/swapdb
Redis::del

Redis|array time()

Retrieve the server time from the connected Redis instance.

Return Value

Redis|array

two element array consisting of a Unix Timestamp and the number of microseconds elapsed since the second.


<?php
$redis = new Redis(['host' => 'localhost']);

// Array
// (
//     [0] => 1667271026
//     [1] => 355678
// )
print_r($redis->time());

See also

https://redis.io/commands/time

Redis|int|false ttl(string $key)

Get the amount of time a Redis key has before it will expire, in seconds.

Parameters

string $key

The Key we want the TTL for.

Return Value

Redis|int|false

(a) The number of seconds until the key expires, or -1 if the key has no expiration, and -2 if the key does not exist. In the event of an error, this command will return false.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->multi()
      ->setex('expires_in_60s', 60, 'test')
      ->set('doesnt_expire', 'persistent')
      ->del('not_a_key')
      ->exec();

// Returns <= 60
$redis->ttl('expires_in_60s');

// Returns -1
$redis->ttl('doesnt_expire');

// Returns -2 (key doesn't exist)
$redis->ttl('not_a_key');

?>

Redis|int|false type(string $key)

Get the type of a given Redis key.

Parameters

string $key

The key to check

Return Value

Redis|int|false

The Redis type constant or false on failure.

The Redis class defines several type constants that correspond with Redis key types.

Redis::REDIS_NOT_FOUND
Redis::REDIS_STRING
Redis::REDIS_SET
Redis::REDIS_LIST
Redis::REDIS_ZSET
Redis::REDIS_HASH
Redis::REDIS_STREAM

See also

https://redis.io/commands/type

Delete one or more keys from the Redis database. Unlike this operation, the actual deletion is asynchronous, meaning it is safe to delete large keys without fear of Redis blocking for a long period of time.

Parameters

array|string $key
string ...$other_keys

If the first argument passed to this method was a string you may pass any number of additional key names.

Return Value

Redis|int|false

The number of keys deleted or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

// OPTION 1:  Called with a single array of keys
$redis->unlink(['key1', 'key2', 'key3']);

// OPTION 2:  Called with a variadic number of arguments
$redis->unlink('key1', 'key2', 'key3');
?>

See also

https://redis.io/commands/unlink
https://redis.io/commands/del
Redis::del

Redis|array|bool unsubscribe(array $channels)

Unsubscribe from one or more subscribed channels.

Parameters

array $channels

Return Value

Redis|array|bool

See also

https://redis.io/commands/unsubscribe
Redis::subscribe

Redis|bool unwatch()

Remove any previously WATCH'ed keys in a transaction.

Return Value

Redis|bool

on success and false on failure.

See also

https://redis.io/commands/unwatch
https://redis.io/commands/unwatch
Redis::watch

bool|Redis watch(array|string $key, string ...$other_keys)

No description

Parameters

array|string $key
string ...$other_keys

Return Value

bool|Redis

int|false wait(int $numreplicas, int $timeout)

Block the client up to the provided timeout until a certain number of replicas have confirmed recieving them.

Parameters

int $numreplicas

The number of replicas we want to confirm write operaions

int $timeout

How long to wait (zero meaning forever).

Return Value

int|false

The number of replicas that have confirmed or false on failure.

See also

https://redis.io/commands/wait

int|false xack(string $key, string $group, array $ids)

No description

Parameters

string $key
string $group
array $ids

Return Value

int|false

Redis|string|false xadd(string $key, string $id, array $values, int $maxlen = 0, bool $approx = false, bool $nomkstream = false)

Append a message to a stream.

Parameters

string $key

The stream name.

string $id

The ID for the message we want to add. This can be the special value '' which means Redis will generate the ID that appends the message to the end of the stream. It can also be a value in the form - which will generate an ID that appends to the end ot entries with the same value (if any exist).

array $values
int $maxlen

If specified Redis will append the new message but trim any number of the oldest messages in the stream until the length is <= $maxlen.

bool $approx

Used in conjunction with $maxlen, this flag tells Redis to trim the stream but in a more efficient way, meaning the trimming may not be exactly to $maxlen values.

bool $nomkstream

If passed as TRUE, the stream must exist for Redis to append the message.

</php
<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('ds9-season-1');

$redis->xAdd('ds9-season-1', '1-1', ['title' => 'Emissary Part 1']);
$redis->xAdd('ds9-season-1', '1-2', ['title' => 'A Man Alone']);
$redis->xAdd('ds9-season-1', '1-3', ['title' => 'Emissary Part 2']);
$redis->xAdd('ds9-season-1', '1-4', ['title' => 'Past Prologue']);

// Array
// (
//     [1-1] => Array
//         (
//             [title] => Emissary Part 1
//         )
//
//     [1-2] => Array
//         (
//             [title] => A Man Alone
//         )
//
// )
$redis->xRange('ds9-season-1', '1-1', '1-2');
?>
?>

Return Value

Redis|string|false

See also

https://redis.io/commands/xadd

Redis|bool|array xautoclaim(string $key, string $group, string $consumer, int $min_idle, string $start, int $count = -1, bool $justid = false)

No description

Parameters

string $key
string $group
string $consumer
int $min_idle
string $start
int $count
bool $justid

Return Value

Redis|bool|array

Redis|bool|array xclaim(string $key, string $group, string $consumer, int $min_idle, array $ids, array $options)

No description

Parameters

string $key
string $group
string $consumer
int $min_idle
array $ids
array $options

Return Value

Redis|bool|array

Redis|int|false xdel(string $key, array $ids)

Remove one or more specific IDs from a stream.

Parameters

string $key

The stream to modify.

array $ids

One or more message IDs to remove.

Return Value

Redis|int|false

The number of messages removed or false on failure.

$redis = new Redis(['host' => 'localhost']);

$redis->del('stream');

for ($a = 1; $a <= 3; $a++) {
    for ($b = 1; $b <= 2; $b++) {
        $redis->xAdd('stream', "$a-$b", ['id' => "$a-$b"]);
    }
}

// Remove some elements
$redis->xDel('stream', ['1-1', '2-1', '3-1']);

// Array
// (
//     [1-2] => Array
//         (
//             [id] => 1-2
//         )
//
//     [2-2] => Array
//         (
//             [id] => 2-2
//         )
//
//     [3-2] => Array
//         (
//             [id] => 3-2
//         )
//
// )
$redis->xRange('stream', '-', '+');
?>

mixed xgroup(string $operation, string $key = null, string $group = null, string $id_or_consumer = null, bool $mkstream = false, int $entries_read = -2)

XGROUP

Perform various operation on consumer groups for a particular Redis STREAM. What the command does is primarily based on which operation is passed.

Parameters

string $operation

The subcommand you intend to execute. Valid options are as follows 'HELP' - Redis will return information about the command Requires: none 'CREATE' - Create a consumer group. Requires: Key, group, consumer. 'SETID' - Set the ID of an existing consumer group for the stream. Requires: Key, group, id. 'CREATECONSUMER' - Create a new consumer group for the stream. You must also pass key, group, and the consumer name you wish to create. Requires: Key, group, consumer. 'DELCONSUMER' - Delete a consumer from group attached to the stream. Requires: Key, group, consumer. 'DESTROY' - Delete a consumer group from a stream. Requires: Key, group.

string $key

The STREAM we're operating on.

string $group

The consumer group we want to create/modify/delete.

string $id_or_consumer

The STREAM id (e.g. '$') or consumer group. See the operation section for information about which to send.

bool $mkstream

This flag may be sent in combination with the 'CREATE' operation, and cause Redis to also create the STREAM if it doesn't currently exist.

int $entries_read

Return Value

mixed

This command return various results depending on the operation performed.

See also

https://redis.io/commands/xgroup/

mixed xinfo(string $operation, string|null $arg1 = null, string|null $arg2 = null, int $count = -1)

Retrieve information about a stream key.

Parameters

string $operation

The specific info operation to perform.

string|null $arg1

The first argument (depends on operation)

string|null $arg2

The second argument

int $count

The COUNT argument to XINFO STREAM

Return Value

mixed

This command can return different things depending on the operation being called.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('stream');

$redis->xAdd('stream', "0-1", ['payload' => '0-1']);
$redis->xAdd('stream', "0-2", ['payload' => '0-2']);
$redis->xAdd('stream', "0-3", ['payload' => '0-3']);

// Retrieve any consmers for a given key
$redis->xInfo('CONSUMERS', 'stream');

// Retrieve any groups for a given key
$redis->xInfo('GROUPS', 'stream');

// Retrieve general stream information along with messages
$redis->xInfo('STREAM', 'stream');
?>

Redis|int|false xlen(string $key)

Get the number of messages in a Redis STREAM key.

Parameters

string $key

The Stream to check.

Return Value

Redis|int|false

The number of messages or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('stream');
$redis->xadd('stream', '*', ['first' => 'message']);
$redis->xadd('stream', '*', ['second' => 'message']);

// int(2)
$redis->xLen('stream');
?>

See also

https://redis.io/commands/xlen

Redis|array|false xpending(string $key, string $group, string|null $start = null, string|null $end = null, int $count = -1, string|null $consumer = null)

Interact with stream messages that have been consumed by a consumer group but not yet acknowledged with XACK.

Parameters

string $key

The stream to inspect.

string $group

The user group we want to see pending messages from.

string|null $start

The minimum ID to consider.

string|null $end
int $count

Optional maximum number of messages to return.

string|null $consumer

If provided, limit the returned messages to a specific consumer.

Return Value

Redis|array|false

The pending messages belonging to the stream or false on failure.

See also

https://redis.io/commands/xpending
https://redis.io/commands/xreadgroup

Redis|array|bool xrange(string $key, string $start, string $end, int $count = -1)

Get a range of entries from a STREAM key.

Parameters

string $key

The stream key name to list.

string $start

The minimum ID to return.

string $end

The maximum ID to return.

int $count

An optional maximum number of entries to return.

Return Value

Redis|array|bool

The entries in the stream within the requested range or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('stream');

for ($i = 0; $i < 2; $i++) {
    for ($j = 1; $j <= 2; $j++) {
        $redis->xAdd('stream', "$i-$j", ['message' => "$i:$j"]);
    }
}

//Array
//(
//    [0-1] => Array
//        (
//            [message] => 0:1
//        )
//
//    [0-2] => Array
//        (
//            [message] => 0:2
//        )
//
//)
$redis->xRange('stream', '0-1', '0-2');

// '-' and '+' are special values which mean 'minimum possible',
// and 'maximum possible' id, respectively.
$redis->xRange('stream', '-', '+');
?>

See also

https://redis.io/commands/xrange

Redis|array|bool xread(array $streams, int $count = -1, int $block = -1)

Consume one or more unconsumed elements in one or more streams.

Parameters

array $streams

An associative array with stream name keys and minimum id values.

int $count

An optional limit to how many entries are returnd per stream

int $block

An optional maximum number of milliseconds to block the caller if no data is available on any of the provided streams.

$redis = new Redis(['host' => 'localhost']);

$redis->del('s03', 's03');

$redis->xAdd('s03', '3-1', ['title' => 'The Search, Part I']);
$redis->xAdd('s03', '3-2', ['title' => 'The Search, Part II']);
$redis->xAdd('s03', '3-3', ['title' => 'The House Of Quark']);

$redis->xAdd('s04', '4-1', ['title' => 'The Way of the Warrior']);
$redis->xAdd('s04', '4-3', ['title' => 'The Visitor']);
$redis->xAdd('s04', '4-4', ['title' => 'Hippocratic Oath']);

// Array
// (
//     [s03] => Array
//         (
//             [3-3] => Array
//                 (
//                     [title] => The House Of Quark
//                 )
//
//         )
//
//     [s04] => Array
//         (
//             [4-3] => Array
//                 (
//                     [title] => The Visitor
//                 )
//
//             [4-4] => Array
//                 (
//                     [title] => Hippocratic Oath
//                 )
//
//         )
//
// )
print_r($redis->xRead(['s03' => '3-2', 's04' => '4-1']));

Return Value

Redis|array|bool

See also

https://redis.io/commands/xread

Redis|array|bool xreadgroup(string $group, string $consumer, array $streams, int $count = 1, int $block = 1)

Read one or more messages using a consumer group.

Parameters

string $group

The consumer group to use.

string $consumer

The consumer to use.

array $streams

An array of stream names and message IDs

int $count

Optional maximum number of messages to return

int $block

How long to block if there are no messages available.

Return Value

Redis|array|bool

Zero or more unread messages or false on failure.

<?php

$redis = new Redis(['host' => 'localhost']);

$redis->del('episodes');

// Create a consumer group (and stream)
$redis->xGroup('CREATE', 'episodes', 'ds9', '0-0', true);

// Add a couple of messages to the stream
$redis->xAdd('episodes', '1-1', ['title' => 'Emissary: Part 1']);
$redis->xAdd('episodes', '1-2', ['title' => 'A Man Alone']);

// Now read some messages with our consumer group
$messages = $redis->xReadGroup('ds9', 'sisko', ['episodes' => '>']);

// After having read the two messages, add another
$redis->xAdd('episodes', '1-3', ['title' => 'Emissary: Part 2']);

// Acknowledge the first two read messages
foreach ($messages as $stream => $stream_messages) {
    $ids = array_keys($stream_messages);
    $redis->xAck('stream', 'ds9', $ids);
}

// We can now pick up where we left off, and will only get the final message
$msgs = $redis->xReadGroup('ds9', 'sisko', ['episodes' => '>']);

// array(1) {
//   ["episodes"]=>
//   array(1) {
//     ["1-3"]=>
//     array(1) {
//       ["title"]=>
//       string(16) "Emissary: Part 2"
//     }
//   }
// }
var_dump($msgs);
?>

Redis|array|bool xrevrange(string $key, string $end, string $start, int $count = -1)

Get a range of entries from a STREAM ke in reverse cronological order.

Parameters

string $key

The stream key to query.

string $end

The maximum message ID to include.

string $start

The minimum message ID to include.

int $count

An optional maximum number of messages to include.

Return Value

Redis|array|bool

The entries within the requested range, from newest to oldest.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('stream');

for ($i = 0; $i < 2; $i++) {
    for ($j = 1; $j <= 2; $j++) {
        $redis->xAdd('stream', "$i-$j", ['message' => "$i:$j"]);
    }
}

// Array
// (
//     [0-2] => Array
//         (
//             [message] => 0:2
//         )
//
//     [0-1] => Array
//         (
//             [message] => 0:1
//         )
//
// )
$redis->xRevRange('stream', '0-2', '0-1');

// '-' and '+' are special values which mean 'minimum possible',
// and 'maximum possible' id, respectively.
$redis->xRevRange('stream', '+', '-');
?>

See also

https://redis.io/commands/xrevrange
https://redis.io/commands/xrange

Redis|int|false xtrim(string $key, string $threshold, bool $approx = false, bool $minid = false, int $limit = -1)

Truncate a STREAM key in various ways.

Parameters

string $key

The STREAM key to trim.

string $threshold

This can either be a maximum length, or a minimum id. MAXLEN - An integer describing the maximum desired length of the stream after the command. MINID - An ID that will become the new minimum ID in the stream, as Redis will trim all messages older than this ID.

bool $approx

Whether redis is allowed to do an approximate trimming of the stream. This is more efficient for Redis given how streams are stored internally.

bool $minid

When set to true, users should pass a minimum ID to the $threshold argument.

int $limit

An optional upper bound on how many entries to trim during the command.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('stream');
$redis->xAdd('stream', '1-1', ['one' => 'one']);
$redis->xAdd('stream', '1-2', ['one' => 'two']);
$redis->xAdd('stream', '2-1', ['two' => 'one']);
$redis->xAdd('stream', '2-2', ['two' => 'two']);

// Trim to three elemn
$redis->xTrim('stream', 3);

// Array
// (
//     [1-2] => Array
//         (
//             [one] => two
//         )
//
//     [2-1] => Array
//         (
//             [two] => one
//         )
//
//     [2-2] => Array
//         (
//             [two] => two
//         )
//
// )
$redis->xRange('stream', '-', '+');

// Now let's trim everything older than '2-1'
$redis->xTrim('stream', '2-1', false, true);

// Array
// (
//     [2-1] => Array
//         (
//             [two] => one
//         )
//
//     [2-2] => Array
//         (
//             [two] => two
//         )
//
// )
print_r($redis->xRange('stream', '-', '+'));
?>

Return Value

Redis|int|false

See also

https://redis.io/commands/xtrim

Redis|int|false zAdd(string $key, array|float $score_or_options, mixed ...$more_scores_and_mems)

Add one or more elements and scores to a Redis sorted set.

Parameters

string $key

The sorted set in question.

array|float $score_or_options

Either the score for the first element, or an array containing one or more options for the operation.

mixed ...$more_scores_and_mems

A variadic number of additional scores and members.

Following is information about the options that may be passed as the scond argument:

$options = [
    'NX',       # Only update elements that already exist
    'NX',       # Only add new elements but don't update existing ones.

    'LT'        # Only update existing elements if the new score is less than the existing one.
    'GT'        # Only update existing elements if the new score is greater than the existing one.

    'CH'        # Instead of returning the number of elements added, Redis will return the number
                # Of elements that were changed in the operation.

    'INCR'      # Instead of setting each element to the provide score, increment the elemnt by the
                # provided score, much like ZINCRBY.  When this option is passed, you may only
                # send a single score and member.
];

Note:  'GX', 'LT', and 'NX' cannot be passed together, and PhpRedis will send whichever one is last in
       the options array.

<?php $redis = new Redis(['host' => 'localhost']);

$redis->del('zs');

// Add three new elements to our zset $redis->zadd('zs', 1, 'first', 2, 'second', 3, 'third');

// Array // ( // [first] => 1 // [second] => 2 // [third] => 3 // ) $redis->zRange('zs', 0, -1, true);

// Update only existing elements. Note that 'new-element' isn't added $redis->zAdd('zs', ['XX'], 8, 'second', 99, 'new-element');

// Array // ( // [first] => 1 // [third] => 3 // [second] => 8 // ) print_r($redis->zRange('zs', 0, -1, true)); ?>

Return Value

Redis|int|false

See also

https://redis.io/commands/zadd

Redis|int|false zCard(string $key)

Return the number of elements in a sorted set.

Parameters

string $key

The sorted set to retreive cardinality from.

Return Value

Redis|int|false

The number of elements in the set or false on failure

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('zs');
$redis->zAdd('zs', 0, 'a', 1, 'b', 2, 'c');

// count(['a', 'b', 'c']) == 3
$redis->zCard('zs');
?>

See also

https://redis.io/commands/zcard

Redis|int|false zCount(string $key, string $start, string $end)

Count the number of members in a sorted set with scores inside a provided range.

Parameters

string $key

The sorted set to check.

string $start
string $end

Return Value

Redis|int|false

See also

https://redis.io/commands/zcount

Redis|float|false zIncrBy(string $key, float $value, mixed $member)

Create or increment the score of a member in a Redis sorted set

Parameters

string $key

The sorted set in question.

float $value

How much to increment the score.

mixed $member

Return Value

Redis|float|false

The new score of the member or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('zs');
$redis->zAdd('zs', 0, 'apples', 2, 'bananas');

// 2 + 5.0 == 7
print_r($redis->zIncrBy('zs', 5.0, 'bananas'));

// new element so 0 + 2.0 == 2
print_r($redis->zIncrBy('zs', 2.0, 'eggplants'));
?>

See also

https://redis.io/commands/zincrby

Redis|int|false zLexCount(string $key, string $min, string $max)

Count the number of elements in a sorted set whos members fall within the provided lexographical range.

Parameters

string $key

The sorted set to check.

string $min

The minimum matching lexographical string

string $max

The maximum matching lexographical string

Return Value

Redis|int|false

The number of members that fall within the range or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('captains');
$redis->zAdd('captains', 0, 'Janeway', 0, 'Kirk', 0, 'Picard', 0, 'Sisko', 0, 'Archer');

count(['Archer', 'Janeway', 'Kirk', 'Picard']) == 4
$redis->zLexCount('captains', '[A', '[S');

count(['Kirk', 'Picard']) == 2
$redis->zRangeByLex('captains', '[A', '[S', 2, 2);
?>

See also

https://redis.io/commands/zlexcount

Redis|array|false zMscore(string $key, mixed $member, mixed ...$other_members)

Retrieve the score of one or more members in a sorted set.

Parameters

string $key

The sorted set

mixed $member

The first member to return the score from

mixed ...$other_members

One or more additional members to return the scores of.

Return Value

Redis|array|false

An array of the scores of the requested elements.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('zs');

$redis->zAdd('zs', 0, 'zero', 1, 'one', 2, 'two', 3, 'three');

// array(2) {
//   [0]=>
//   float(0)
//   [1]=>
//   float(2)
// }
$redis->zMScore('zs', 'zero', 'two');

// array(2) {
//   [0]=>
//   float(1)
//   [1]=>
//   bool(false)
// }
$redis->zMScore('zs', 'one', 'not-a-member');
?>

See also

https://redis.io/commands/zmscore

Redis|array|false zPopMax(string $key, int $count = null)

Pop one or more of the highest scoring elements from a sorted set.

Parameters

string $key

The sorted set to pop elements from.

int $count

An optional count of elements to pop.

Return Value

Redis|array|false

All of the popped elements with scores or false on fialure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('zs');
$redis->zAdd('zs', 0, 'zero', 1, 'one', 2, 'two', 3, 'three');

// Array
// (
//     [three] => 3
// )
print_r($redis->zPopMax('zs'));

// Array
// (
//     [two] => 2
//     [one] => 1
// )
print_r($redis->zPopMax('zs', 2));
?>

See also

https://redis.io/commands/zpopmax

Redis|array|false zPopMin(string $key, int $count = null)

Pop one or more of the lowest scoring elements from a sorted set.

Parameters

string $key

The sorted set to pop elements from.

int $count

An optional count of elements to pop.

Return Value

Redis|array|false

The popped elements with their scores or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('zs');
$redis->zAdd('zs', 0, 'zero', 1, 'one', 2, 'two', 3, 'three');

// Array
// (
//     [zero] => 0
// )
$redis->zPopMin('zs');

// Array
// (
//     [one] => 1
//     [two] => 2
// )
$redis->zPopMin('zs', 2);
?>

See also

https://redis.io/commands/zpopmin

Redis|array|false zRange(string $key, mixed $start, mixed $end, array|bool|null $options = null)

Retrieve a range of elements of a sorted set between a start and end point.

How the command works in particular is greatly affected by the options that are passed in.

Parameters

string $key

The sorted set in question.

mixed $start

The starting index we want to return.

mixed $end

The final index we want to return.

array|bool|null $options

This value may either be an array of options to pass to the command, or for historical purposes a boolean which controls just the 'WITHSCORES' option.

Return Value

Redis|array|false

An array with matching elements or false on failure.

Detailed description of options array:

<?php
$options = [
    'WITHSCORES' => true,     // Return both scores and members.
    'LIMIT'      => [10, 10], // Start at offset 10 and return 10 elements.
    'REV'                     // Return the elements in reverse order
    'BYSCORE',                // Treat `start` and `end` as scores instead
    'BYLEX'                   // Treat `start` and `end` as lexicographical values.
];
?>

Note: 'BYLEX' and 'BYSCORE' are mutually exclusive.

See also

https://redis.io/commands/zrange/

Redis|array|false zRangeByLex(string $key, string $min, string $max, int $offset = -1, int $count = -1)

Retrieve a range of elements from a sorted set by legographical range.

Parameters

string $key

The sorted set to retreive elements from

string $min

The minimum legographical value to return

string $max

The maximum legographical value to return

int $offset

An optional offset within the matching values to return

int $count

An optional count to limit the replies to (used in conjunction with offset)

Return Value

Redis|array|false

An array of matching elements or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('captains');
$redis->zAdd('captains', 0, 'Janeway', 0, 'Kirk', 0, 'Picard', 0, 'Sisko', 0, 'Archer');

// Array
// (
//     [0] => Archer
//     [1] => Janeway
//     [2] => Kirk
//     [3] => Picard
// )
$redis->zRangeByLex('captains', '[A', '[S');

// Array
// (
//     [0] => Kirk
//     [1] => Picard
// )
$redis->zRangeByLex('captains', '[A', '[S', 2, 2);
?>

See also

https://redis.io/commands/zrangebylex

Redis|array|false zRangeByScore(string $key, string $start, string $end, array $options = [])

Retrieve a range of members from a sorted set by their score.

Parameters

string $key

The sorted set to query.

string $start

The minimum score of elements that Redis should return.

string $end

The maximum score of elements that Redis should return.

array $options

Options that change how Redis will execute the command.

OPTION TYPE MEANING 'WITHSCORES' bool Whether to also return scores. 'LIMIT' [offset, count] Limit the reply to a subset of elements.

Return Value

Redis|array|false

The number of matching elements or false on failure.

</php
$redis = new Redis(['host' => 'localhost']);

$redis->del('zs');

for ($i = 0; $i < 50; $i++) {
    $redis->zAdd('zs', $i, "mem:$i");
}

// Array
// (
//     [0] => mem:0
//     [1] => mem:1
//     [2] => mem:2
//     [3] => mem:3
//     [4] => mem:4
// )
$redis->zRangeByScore('zs', 0, 4);

// Array
// (
//     [mem:20] => 20
//     [mem:21] => 21
//     [mem:22] => 22
//     [mem:23] => 23
//     [mem:24] => 24
//     [mem:25] => 25
//     [mem:26] => 26
//     [mem:27] => 27
//     [mem:28] => 28
//     [mem:29] => 29
//     [mem:30] => 30
// )
$redis->zRangeByScore('zs', 20, 30, ['WITHSCORES' => true]);

// Array
// (
//     [mem:25] => 25
//     [mem:26] => 26
//     [mem:27] => 27
//     [mem:28] => 28
//     [mem:29] => 29
// )
$redis->zRangeByScore('zs', 20, 30, ['WITHSCORES' => true, 'LIMIT' => [5, 5]]);
?>

See also

https://redis.io/commands/zrangebyscore

Redis|int|false zrangestore(string $dstkey, string $srckey, string $start, string $end, array|bool|null $options = NULL)

This command is similar to ZRANGE except that instead of returning the values directly it will store them in a destination key provided by the user

Parameters

string $dstkey

The key to store the resulting element(s)

string $srckey

The source key with element(s) to retrieve

string $start

The starting index to store

string $end

The ending index to store

array|bool|null $options

Our options array that controls how the command will function.

Return Value

Redis|int|false

The number of elements stored in $dstkey or false on failure.

See Redis::zRange for a full description of the possible options.

See also

https://redis.io/commands/zrange/
Redis::zRange

Redis|string|array zRandMember(string $key, array $options = null)

Retrieve one or more random members from a Redis sorted set.

Parameters

string $key

The sorted set to pull random members from.

array $options

One or more options that determine exactly how the command operates.

                   OPTION       TYPE     MEANING
                   'COUNT'      int      The number of random members to return.
                   'WITHSCORES' bool     Whether to return scores and members instead of
                                         just members.
<?php
$redis = new Redis(['host' => 'localhost']);

$redis->multi()->del('zs')->zadd('zs', 1, 'one', 2, 'two', 3, 'three')->exec();

// Return two random members from our set, with scores
$redis->zRandMember('zs', ['COUNT' => 2, 'WITHSCORES' => true]);

?>

Return Value

Redis|string|array

See also

https://redis.io/commands/zrandmember

Redis|int|false zRank(string $key, mixed $member)

Get the rank of a member of a sorted set, by score.

Parameters

string $key

The sorted set to check.

mixed $member

Return Value

Redis|int|false

See also

https://redis.io/commands/zrank

Redis|int|false zRem(mixed $key, mixed $member, mixed ...$other_members)

Remove one or more members from a Redis sorted set.

Parameters

mixed $key

The sorted set in question.

mixed $member

The first member to remove.

mixed ...$other_members

One or more members to remove passed in a variadic fashion.

Return Value

Redis|int|false

The number of members that were actually removed or false on failure.


<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('zs');

for ($i = 0; $i < 10; $i++) {
    $redis->zAdd('zs', $i, "mem:$i");
}

// Remove a few elements
$redis->zRem('zs', 'mem:0', 'mem:1', 'mem:2', 'mem:6', 'mem:7', 'mem:8', 'mem:9');

// Array
// (
//     [0] => mem:3
//     [1] => mem:4
//     [2] => mem:5
// )
$redis->zRange('zs', 0, -1);
?>

See also

https://redis.io/commands/zrem

Redis|int|false zRemRangeByLex(string $key, string $min, string $max)

Remove zero or more elements from a Redis sorted set by legographical range.

Parameters

string $key

The sorted set to remove elements from.

string $min

The start of the lexographical range to remove.

string $max

The end of the lexographical range to remove

Return Value

Redis|int|false

The number of elements removed from the set or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->pipeline()->del('zs')
               ->zAdd('zs', 1, 'apple', 2, 'banana', 3, 'carrot', 4, 'date', 5, 'eggplant')
               ->exec();

// Remove a* (inclusive) .. b* (exclusive), meaning 'apple' will be removed, but 'banana' not
$redis->zRemRangeByLex('zs', '[a', '(b');

// Array
// (
//     [0] => banana
//     [1] => carrot
//     [2] => date
//     [3] => eggplant
// )
print_r($redis->zRange('zs', 0, -1));

// Remove the elements between 'banana' and 'eggplant'
$redis->zRemRangeByLex('zs', '(banana', '(eggplant');

// Array
// (
//     [0] => banana
//     [1] => eggplant
// )
print_r($redis->zRange('zs', 0, -1));
?>

See also

https://redis.io/commands/zremrangebylex
\Redis::zrangebylex()

Redis|int|false zRemRangeByRank(string $key, int $start, int $end)

Remove one or more members of a sorted set by their rank.

Parameters

string $key

The sorted set where we wnat to remove members.

int $start

The rank when we want to start removing members

int $end

The rank we want to stop removing membersk.

Return Value

Redis|int|false

The number of members removed from the set or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('zs');
$redis->zAdd('zs', 0, 'zeroth', 1, 'first', 2, 'second', 3, 'third', 4, 'fourth');

// Remove ranks 0..3
$redis->zRemRangeByRank('zs', 0, 3);

// Array
// (
//     [0] => fourth
// )
$redis->zRange('zs', 0, -1);
?>

See also

https://redis.io/commands/zremrangebyrank

Redis|int|false zRemRangeByScore(string $key, string $start, string $end)

Remove one or more members of a sorted set by their score.

Parameters

string $key

The sorted set where we wnat to remove members.

string $start

The lowest score to remove.

string $end

The highest score to remove.

Return Value

Redis|int|false

The number of members removed from the set or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('zs');
$redis->zAdd('zs', 3, 'three', 5, 'five', 7, 'seven', 7, 'seven-again', 13, 'thirteen', 22, 'twenty-two');

// Removes every member with scores >= 7 and scores <= 13.
$redis->zRemRangeByScore('zs', 7, 13);

// Array
// (
//     [0] => three
//     [1] => five
//     [2] => twenty-two
// )
$redis->zRange('zs', 0, -1);
?>

See also

https://redis.io/commands/zremrangebyrank

Redis|array|false zRevRange(string $key, int $start, int $end, mixed $scores = null)

List the members of a Redis sorted set in reverse order

Parameters

string $key

The sorted set in question.

int $start

The index to start listing elements

int $end

The index to stop listing elements.

mixed $scores

Return Value

Redis|array|false

The members (and possibly scores) of the matching elements or false on failure.

$redis = new Redis(['host' => 'localhost']);

$redis->del('zs'); $redis->zAdd('zs', 1, 'one', 2, 'two', 5, 'five', 10, 'ten');

// Array // ( // [0] => ten // [1] => five // [2] => two // [3] => one // ) print_r($redis->zRevRange('zs', 0, -1));

// Array // ( // [0] => two // [1] => one // ) print_r($redis->zRevRange('zs', 2, 3));

// Additionally, you may pass true or ['withscores' => true] to tell redis to return scores // as well as members. $redis->zRevRange('zs', 0, -1, true); $redis->zRevRange('zs', 0, -1, ['withscores' => true]); ?>

Redis|array|false zRevRangeByLex(string $key, string $max, string $min, int $offset = -1, int $count = -1)

List members of a Redis sorted set within a legographical range, in reverse order.

Parameters

string $key

The sorted set to list

string $max
string $min

The maximum legographical element to include in the result.

int $offset

An option offset within the matching elements to start at.

int $count

An optional count to limit the replies to.

Return Value

Redis|array|false

The matching members or false on failure.

<?php

$redis = new Redis(['host' => 'localhost']);

$redis->del('captains');
$redis->zAdd('captains', 0, 'Janeway', 0, 'Picard', 0, 'Kirk', 0, 'Archer');

// Array
// (
//     [0] => Picard
//     [1] => Kirk
//     [2] => Janeway
// )
$redis->zRevRangeByLex('captains', '[Q', '[J');

// Array
// (
//     [0] => Kirk
//     [1] => Janeway
// )
$redis->zRevRangeByLex('captains', '[Q', '[J', 1, 2);
?>

See also

https://redis.io/commands/zrevrangebylex
\Redis::zrangebylex()

Redis|array|false zRevRangeByScore(string $key, string $max, string $min, array|bool $options = [])

List elements from a Redis sorted set by score, highest to lowest

Parameters

string $key

The sorted set to query.

string $max

The highest score to include in the results.

string $min

The lowest score to include in the results.

array|bool $options

An options array that modifies how the command executes.

$options = [
    'WITHSCORES' => true|false # Whether or not to return scores
    'LIMIT' => [offset, count] # Return a subset of the matching members
];

NOTE: For legacy reason, you may also simply pass true for the options argument, to mean WITHSCORES.

Return Value

Redis|array|false

The matching members in reverse order of score or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('oldest-people');

$redis->zadd('oldest-people', 122.4493, 'Jeanne Calment', 119.2932, 'Kane Tanaka',
                              119.2658, 'Sarah Knauss',   118.7205, 'Lucile Randon',
                              117.7123, 'Nabi Tajima',    117.6301, 'Marie-Louise Meilleur',
                              117.5178, 'Violet Brown',   117.3753, 'Emma Morano',
                              117.2219, 'Chiyo Miyako',   117.0740, 'Misao Okawa');

// Array
// (
//     [0] => Kane Tanaka
//     [1] => Sarah Knauss
// )
$redis->zRevRangeByScore('oldest-people', 122, 119);

//Array
//(
//    [0] => Jeanne Calment
//    [1] => Kane Tanaka
//    [2] => Sarah Knauss
//    [3] => Lucile Randon
//)
$redis->zRevRangeByScore('oldest-people', 'inf', 118);

// Array
// (
//     [0] => Emma Morano
// )
$redis->zRevRangeByScore('oldest-people', '117.5', '-inf', ['LIMIT' => [0, 1]]);
?>

Redis|int|false zRevRank(string $key, mixed $member)

Retrieve a member of a sorted set by reverse rank.

Parameters

string $key

The sorted set to query.

mixed $member

The member to look up.

Return Value

Redis|int|false

The reverse rank (the rank if counted high to low) of the member or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('ds9-characters');

$redis->zAdd('ds9-characters', 10, 'Sisko', 9, 'Garak', 8, 'Dax', 7, 'Odo');

// Highest score, reverse rank 0
$redis->zrevrank('ds9-characters', 'Sisko');

// Second highest score, reverse rank 1
$redis->zrevrank('ds9-characters', 'Garak');
?>

See also

https://redis.io/commands/zrevrank

Redis|float|false zScore(string $key, mixed $member)

Get the score of a member of a sorted set.

Parameters

string $key

The sorted set to query.

mixed $member

The member we wish to query.

Return Value

Redis|float|false

score of the requested element or false if it is not found.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('telescopes');

$redis->zAdd('telescopes', 11.9, 'LBT', 10.4, 'GTC', 10, 'HET');

foreach ($redis->zRange('telescopes', 0, -1) as $name) {
    // Get the score for this member
    $aperature = $redis->zScore('telescopes', $name);

    echo "The '$name' telescope has an effective aperature of: $aperature meters\n";
}
?>

See also

https://redis.io/commands/zscore

Redis|array|false zdiff(array $keys, array $options = null)

Given one or more sorted set key names, return every element that is in the first set but not any of the others.

Parameters

array $keys

One ore more sorted sets.

array $options

An array which can contain ['WITHSCORES' => true] if you want Redis to return members and scores.

Return Value

Redis|array|false

An array of members or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('primes', 'evens', 'mod3');

$redis->zAdd('primes', 1, 'one', 3, 'three', 5, 'five');
$redis->zAdd('evens', 2, 'two', 4, 'four');
$redis->zAdd('mod3', 3, 'three', 6, 'six');

// Array
// (
//     [0] => one
//     [1] => five
// )
print_r($redis->zDiff(['primes', 'evens', 'mod3']));
?>

See also

https://redis.io/commands/zdiff

Redis|int|false zdiffstore(string $dst, array $keys)

Store the difference of one or more sorted sets in a destination sorted set.

Parameters

string $dst
array $keys

One or more source key names

Return Value

Redis|int|false

The number of elements stored in the destination set or false on failure.

NOTE: See Redis::zdiff() for a more detailed description of how the diff operation works.

See also

https://redis.io/commands/zdiff
Redis::zdiff

Redis|array|false zinter(array $keys, array|null $weights = null, array|null $options = null)

Compute the intersection of one or more sorted sets and return the members

Parameters

array $keys

One ore more sorted sets.

array|null $weights

An optional array of weights to be applied to each set when performing the intersection.

array|null $options

Options for how Redis should combine duplicate elements when performing the intersection. See Redis::zunion() for details.

Return Value

Redis|array|false

All of the members that exist in every set.

<?php

$redis = new Redis(['host' => 'localhost']);

$redis->del('tng', 'ds9');

$redis->zAdd('TNG', 2, 'Worf', 2.5, 'Data', 4.0, 'Picard');
$redis->zAdd('DS9', 2.5, 'Worf', 3.0, 'Kira', 4.0, 'Sisko');

// Array
// (
//     [0] => Worf
// )
$redis->zInter(['TNG', 'DS9']);

// Array
// (
//     [Worf] => 4.5
// )
$redis->zInter(['TNG', 'DS9'], NULL, ['withscores' => true]);

// Array
// (
//     [Worf] => 2.5
// )
$redis->zInter(['TNG', 'DS9'], NULL, ['withscores' => true, 'aggregate' => 'max']);

?>

See also

https://redis.io/commands/zinter

Redis|int|false zintercard(array $keys, int $limit = -1)

Similar to ZINTER but instead of returning the intersected values, this command returns the cardinality of the intersected set.

Parameters

array $keys

One ore more sorted set key names.

int $limit

An optional upper bound on the returned cardinality. If set to a value greater than zero, Redis will stop processing the intersection once the resulting cardinality reaches this limit.

Return Value

Redis|int|false

The cardinality of the intersection or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('zs1', 'zs2');

$redis->zAdd('zs1', 1, 'one', 2, 'two', 3, 'three', 4, 'four');
$redis->zAdd('zs2', 2, 'two', 4, 'four');

// count(['two', 'four']) == 2
$redis->zInterCard(['zs1', 'zs2']);
?>

See also

https://redis.io/commands/zintercard
https://redis.io/commands/zinter
Redis::zinter

Redis|int|false zinterstore(string $dst, array $keys, array|null $weights = null, string|null $aggregate = null)

Compute the intersection of one ore more sorted sets storing the result in a new sorted set.

Parameters

string $dst

The destination sorted set to store the intersected values.

array $keys

One ore more sorted set key names.

array|null $weights

An optional array of floats to weight each passed input set.

string|null $aggregate

An optional aggregation method to use.

'SUM' - Store sum of all intersected members (this is the default). 'MIN' - Store minimum value for each intersected member. 'MAX' - Store maximum value for each intersected member.

Return Value

Redis|int|false

The total number of members writtern to the destination set or false on failure.


<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('zs', 'zs2', 'zs3');
$redis->zAdd('zs1', 3, 'apples', 2, 'pears');
$redis->zAdd('zs2', 4, 'pears', 3, 'bananas');
$redis->zAdd('zs3', 2, 'figs', 3, 'pears');

// Returns 1 (only 'pears' is in every set)
$redis->zInterStore('fruit-sum', ['zs1', 'zs2', 'zs3']);

// Array
// (
//     [pears] => 9
// )
$redis->zRange('fruit-sum', 0, -1, true);

$redis->zInterStore('fruit-max', ['zs1', 'zs2', 'zs3'], NULL, 'MAX');

// Array
// (
//     [pears] => 4
// )
print_r($redis->zRange('fruit-max', 0, -1, true));
?>

See also

https://redis.io/commands/zinterstore
https://redis.io/commands/zinter

Redis|array|false zscan(string $key, int|null $iterator, string|null $pattern = null, int $count = 0)

Scan the members of a sorted set incrementally, using a cursor

Parameters

string $key

The sorted set to scan.

int|null $iterator

A reference to an iterator that should be initialized to NULL initially, that will be updated after each subsequent call to ZSCAN. Once the iterator has returned to zero the scan is complete

string|null $pattern

An optional glob-style pattern that limits which members are returned during the scanning process.

int $count

A hint for Redis that tells it how many elements it should test before returning from the call. The higher the more work Redis may do in any one given call to ZSCAN potentially blocking for longer periods of time.

Return Value

Redis|array|false

An array of elements or false on failure.

NOTE: See Redis::scan() for detailed example code on how to call SCAN like commands.

See also

https://redis.io/commands/zscan
https://redis.io/commands/scan
Redis::scan

Redis|array|false zunion(array $keys, array|null $weights = null, array|null $options = null)

Retrieve the union of one or more sorted sets

Parameters

array $keys

One ore more sorted set key names

array|null $weights

An optional array with floating point weights used when performing the union. Note that if this argument is passed, it must contain the same number of elements as the $keys array.

array|null $options

An array that modifies how this command functions.

$options = [
    // By default when members exist in more than one set Redis will SUM
    // total score for each match.  Instead, it can return the AVG, MIN,
    // or MAX value based on this option.
    'AGGREGATE' => 'sum' | 'min' | 'max'

    // Whether Redis should also return each members aggregated score.
    'WITHSCORES' => true | false
]

Return Value

Redis|array|false

The union of each sorted set or false on failure

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('store1', 'store2', 'store3');
$redis->zAdd('store1', 1, 'apples', 3, 'pears', 6, 'bananas');
$redis->zAdd('store2', 3, 'apples', 5, 'coconuts', 2, 'bananas');
$redis->zAdd('store3', 2, 'bananas', 6, 'apples', 4, 'figs');

// Array
// (
//     [pears] => 3
//     [figs] => 4
//     [coconuts] => 5
//     [apples] => 10
//     [bananas] => 10
// )
$redis->zUnion(['store1', 'store2', 'store3'], NULL, ['withscores' => true]);

// Array
// (
//     [figs] => 2
//     [apples] => 5
//     [pears] => 6
//     [bananas] => 13
// )
$redis->zUnion(['store1', 'store3'], [2, .5], ['withscores' => true]);

// Array
// (
//     [bananas] => 1
//     [apples] => 2
//     [figs] => 2
//     [pears] => 6
// )
$redis->zUnion(['store1', 'store3'], [2, .5], ['withscores' => true, 'aggregate' => 'MIN']);
?>

Redis|int|false zunionstore(string $dst, array $keys, array|null $weights = NULL, string|null $aggregate = NULL)

Perform a union on one or more Redis sets and store the result in a destination sorted set.

Parameters

string $dst

The destination set to store the union.

array $keys

One or more input keys on which to perform our union.

array|null $weights

An optional weights array used to weight each input set.

string|null $aggregate

An optional modifier in how Redis will combine duplicate members. Valid: 'MIN', 'MAX', 'SUM'.

Return Value

Redis|int|false

The number of members stored in the destination set or false on failure.

<?php
$redis = new Redis(['host' => 'localhost']);

$redis->del('zs1', 'zs2', 'zs3');

$redis->zAdd('zs1', 1, 'one', 3, 'three');
$redis->zAdd('zs1', 2, 'two', 4, 'four');
$redis->zadd('zs3', 1, 'one', 7, 'five');

// count(['one','two','three','four','five']) == 5
$redis->zUnionStore('dst', ['zs1', 'zs2', 'zs3']);

// Array
// (
//     [0] => one
//     [1] => two
//     [2] => three
//     [3] => four
//     [4] => five
// )
$redis->zRange('dst', 0, -1);
?>

See also

https://redis.io/commands/zunionstore
Redis::zunion