Skip to content

phpredis/phpredis

develop
Switch branches/tags
Code

Files

Permalink
Failed to load latest commit information.

README.markdown

PhpRedis

Build Status Coverity Scan Build Status PHP version

The phpredis extension provides an API for communicating with the Redis key-value store. It is released under the PHP License, version 3.01. This code has been developed and maintained by Owlient from November 2009 to March 2011.

You can send comments, patches, questions here on github, to n.favrefelix@gmail.com (@yowgi), to michael.grunder@gmail.com (@grumi78) or to p.yatsukhnenko@gmail.com (@yatsukhnenko).

Supporting the project

PhpRedis will always be free and open source software, but if you or your company has found it useful please consider supporting the project. Developing a large, complex, and performant library like PhpRedis takes a great deal of time and effort, and support would be appreciated! ❤️

The best way to support the project is through GitHub sponsors. Many of the reward tiers grant access to our slack channel where myself and Pavlo are regularly available to answer questions. Additionally this will allow you to provide feedback on which fixes and new features to prioritize.

You can also make a one-time contribution with one of the links below.

PayPal Bitcoin Ethereum

Sponsors

Audiomack.com Bluehost.com Object Cache Pro OpenLMS.net

Table of contents


  1. Installing/Configuring
  2. Classes and methods

Installing/Configuring


Installation

For everything you should need to install PhpRedis on your system, see the INSTALL.markdown page.

PHP Session handler

phpredis can be used to store PHP sessions. To do this, configure session.save_handler and session.save_path in your php.ini to tell phpredis where to store the sessions:

session.save_handler = redis
session.save_path = "tcp://host1:6379?weight=1, tcp://host2:6379?weight=2&timeout=2.5, tcp://host3:6379?weight=2&read_timeout=2.5"

session.save_path can have a simple host:port format too, but you need to provide the tcp:// scheme if you want to use the parameters. The following parameters are available:

  • weight (integer): the weight of a host is used in comparison with the others in order to customize the session distribution on several hosts. If host A has twice the weight of host B, it will get twice the amount of sessions. In the example, host1 stores 20% of all the sessions (1/(1+2+2)) while host2 and host3 each store 40% (2/(1+2+2)). The target host is determined once and for all at the start of the session, and doesn't change. The default weight is 1.
  • timeout (float): the connection timeout to a redis host, expressed in seconds. If the host is unreachable in that amount of time, the session storage will be unavailable for the client. The default timeout is very high (86400 seconds).
  • persistent (integer, should be 1 or 0): defines if a persistent connection should be used. (experimental setting)
  • prefix (string, defaults to "PHPREDIS_SESSION:"): used as a prefix to the Redis key in which the session is stored. The key is composed of the prefix followed by the session ID.
  • auth (string, or an array with one or two elements): used to authenticate with the server prior to sending commands.
  • database (integer): selects a different database.

Sessions have a lifetime expressed in seconds and stored in the INI variable "session.gc_maxlifetime". You can change it with ini_set(). The session handler requires a version of Redis supporting EX and NX options of SET command (at least 2.6.12). phpredis can also connect to a unix domain socket: session.save_path = "unix:///var/run/redis/redis.sock?persistent=1&weight=1&database=0".

Session locking

Support: Locking feature is currently only supported for Redis setup with single master instance (e.g. classic master/slave Sentinel environment). So locking may not work properly in RedisArray or RedisCluster environments.

Following INI variables can be used to configure session locking:

; Should the locking be enabled? Defaults to: 0.
redis.session.locking_enabled = 1
; How long should the lock live (in seconds)? Defaults to: value of max_execution_time.
redis.session.lock_expire = 60
; How long to wait between attempts to acquire lock, in microseconds (µs)?. Defaults to: 20000
redis.session.lock_wait_time = 50000
; Maximum number of times to retry (-1 means infinite). Defaults to: 100
redis.session.lock_retries = 2000

Running the unit tests

phpredis uses a small custom unit test suite for testing functionality of the various classes. To run tests, simply do the following:

# Run tests for Redis class (note this is the default)
php tests/TestRedis.php --class Redis

# Run tests for RedisArray class
tests/mkring.sh start
php tests/TestRedis.php --class RedisArray
tests/mkring.sh stop

# Run tests for the RedisCluster class
tests/make-cluster.sh start
php tests/TestRedis.php --class RedisCluster
tests/make-cluster.sh stop

# Run tests for RedisSentinel class
php tests/TestRedis.php --class RedisSentinel

Note that it is possible to run only tests which match a substring of the test itself by passing the additional argument '--test ' when invoking.

# Just run the 'echo' test
php tests/TestRedis.php --class Redis --test echo

Classes and methods


Usage

  1. Class Redis
  2. Class RedisException
  3. Predefined constants

Class Redis


Description: Creates a Redis client

Example
$redis = new Redis();

Starting from version 6.0.0 it's possible to specify configuration options. This allows to connect to the server without explicitly invoking connect command.

Example
$redis = new Redis([
    'host' => '127.0.0.1',
    'port' => 6379,
    'connectTimeout' => 2.5,
    'auth' => ['phpredis', 'phpredis'],
    'ssl' => ['verify_peer' => false],
    'backoff' => [
        'algorithm' => Redis::BACKOFF_ALGORITHM_DECORRELATED_JITTER,
        'base' => 500,
        'cap' => 750,
    ],
]);
Parameters

host: string. can be a host, or the path to a unix domain socket.
port: int (default is 6379, should be -1 for unix domain socket)
connectTimeout: float, value in seconds (default is 0 meaning unlimited)
retryInterval: int, value in milliseconds (optional)
readTimeout: float, value in seconds (default is 0 meaning unlimited)
persistent: mixed, if value is string then it used as persistend id, else value casts to boolean
auth: mixed, authentication information
ssl: array, SSL context options

Class RedisException


phpredis throws a RedisException object if it can't reach the Redis server. That can happen in case of connectivity issues, if the Redis service is down, or if the redis host is overloaded. In any other problematic case that does not involve an unreachable server (such as a key not existing, an invalid command, etc), phpredis will return FALSE.

Predefined constants


Description: Available Redis Constants

Redis data types, as returned by type

Redis::REDIS_STRING - String
Redis::REDIS_SET - Set
Redis::REDIS_LIST - List
Redis::REDIS_ZSET - Sorted set
Redis::REDIS_HASH - Hash
Redis::REDIS_NOT_FOUND - Not found / other

@TODO: OPT_SERIALIZER, AFTER, BEFORE,...

Connection

  1. connect, open - Connect to a server
  2. pconnect, popen - Connect to a server (persistent)
  3. auth - Authenticate to the server
  4. select - Change the selected database for the current connection
  5. swapdb - Swaps two Redis databases
  6. close - Close the connection
  7. setOption - Set client option
  8. getOption - Get client option
  9. ping - Ping the server
  10. echo - Echo the given string

connect, open


Description: Connects to a Redis instance.

Parameters

host: string. can be a host, or the path to a unix domain socket. Starting from version 5.0.0 it is possible to specify schema port: int, optional
timeout: float, value in seconds (optional, default is 0 meaning unlimited)
reserved: should be NULL if retry_interval is specified
retry_interval: int, value in milliseconds (optional)
read_timeout: float, value in seconds (optional, default is 0 meaning unlimited) others: array, with PhpRedis >= 5.3.0, it allows setting auth and stream configuration.

Return value

BOOL: TRUE on success, FALSE on error.

Example
$redis->connect('127.0.0.1', 6379);
$redis->connect('127.0.0.1'); // port 6379 by default
$redis->connect('tls://127.0.0.1', 6379); // enable transport level security.
$redis->connect('tls://127.0.0.1'); // enable transport level security, port 6379 by default.
$redis->connect('127.0.0.1', 6379, 2.5); // 2.5 sec timeout.
$redis->connect('/tmp/redis.sock'); // unix domain socket.
$redis->connect('127.0.0.1', 6379, 1, NULL, 100); // 1 sec timeout, 100ms delay between reconnection attempts.
$redis->connect('/tmp/redis.sock', 0, 1.5, NULL, 0, 1.5); // Unix socket with 1.5s timeouts (connect and read)

/* With PhpRedis >= 5.3.0 you can specify authentication and stream information on connect */
$redis->connect('127.0.0.1', 6379, 1, NULL, 0, 0, ['auth' => ['phpredis', 'phpredis']]);

Note: open is an alias for connect and will be removed in future versions of phpredis.

pconnect, popen


Description: Connects to a Redis instance or reuse a connection already established with pconnect/popen.

The connection will not be closed on end of request until the php process ends. So be prepared for too many open FD's errors (specially on redis server side) when using persistent connections on many servers connecting to one redis server.

Also more than one persistent connection can be made identified by either host + port + timeout or host + persistent_id or unix socket + timeout.

Starting from version 4.2.1, it became possible to use connection pooling by setting INI variable redis.pconnect.pooling_enabled to 1.

This feature is not available in threaded versions. pconnect and popen then working like their non persistent equivalents.

Parameters

host: string. can be a host, or the path to a unix domain socket. Starting from version 5.0.0 it is possible to specify schema port: int, optional
timeout: float, value in seconds (optional, default is 0 meaning unlimited)
persistent_id: string. identity for the requested persistent connection
retry_interval: int, value in milliseconds (optional)
read_timeout: float, value in seconds (optional, default is 0 meaning unlimited)

Return value

BOOL: TRUE on success, FALSE on error.

Example
$redis->pconnect('127.0.0.1', 6379);
$redis->pconnect('127.0.0.1'); // port 6379 by default - same connection like before.
$redis->pconnect('tls://127.0.0.1', 6379); // enable transport level security.
$redis->pconnect('tls://127.0.0.1'); // enable transport level security, port 6379 by default.
$redis->pconnect('127.0.0.1', 6379, 2.5); // 2.5 sec timeout and would be another connection than the two before.
$redis->pconnect('127.0.0.1', 6379, 2.5, 'x'); // x is sent as persistent_id and would be another connection than the three before.
$redis->pconnect('/tmp/redis.sock'); // unix domain socket - would be another connection than the four before.

Note: popen is an alias for pconnect and will be removed in future versions of phpredis.

auth


Description: Authenticate the connection using a password or a username and password. Warning: The password is sent in plain-text over the network.

Parameters

MIXED: password

Return value

BOOL: TRUE if the connection is authenticated, FALSE otherwise.

Note: In order to authenticate with a username and password you need Redis >= 6.0.

Example
/* Authenticate with the password 'foobared' */
$redis->auth('foobared');

/* Authenticate with the username 'phpredis', and password 'haxx00r' */
$redis->auth(['phpredis', 'haxx00r']);

/* Authenticate with the password 'foobared' */
$redis->auth(['foobared']);

/* You can also use an associative array specifying user and pass */
$redis->auth(['user' => 'phpredis', 'pass' => 'phpredis']);
$redis->auth(['pass' => 'phpredis']);

select


Description: Change the selected database for the current connection.

Parameters

INTEGER: dbindex, the database number to switch to.

Return value

TRUE in case of success, FALSE in case of failure.

Example

See method for example: move

swapdb


Description: Swap one Redis database with another atomically

Parameters

INTEGER: db1
INTEGER: db2

Return value

TRUE on success and FALSE on failure.

Note: Requires Redis >= 4.0.0

Example
$redis->swapdb(0, 1); /* Swaps DB 0 with DB 1 atomically */

close


Description: Disconnects from the Redis instance.

Note: Closing a persistent connection requires PhpRedis >= 4.2.0.

Parameters

None.

Return value

BOOL: TRUE on success, FALSE on failure.

setOption


Description: Set client option.

Parameters

parameter name
parameter value

Return value

BOOL: TRUE on success, FALSE on error.

Example
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE);	  // Don't serialize data
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);	  // Use built-in serialize/unserialize
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); // Use igBinary serialize/unserialize
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_MSGPACK);  // Use msgpack serialize/unserialize
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_JSON);  // Use JSON to serialize/unserialize

$redis->setOption(Redis::OPT_PREFIX, 'myAppName:');	// use custom prefix on all keys

/* Options for the SCAN family of commands, indicating whether to abstract
   empty results from the user.  If set to SCAN_NORETRY (the default), phpredis
   will just issue one SCAN command at a time, sometimes returning an empty
   array of results.  If set to SCAN_RETRY, phpredis will retry the scan command
   until keys come back OR Redis returns an iterator of zero
*/
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NORETRY);
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);

/* Scan can also be configured to automatically prepend the currently set PhpRedis
   prefix to any MATCH pattern. */
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_PREFIX);
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NOPREFIX);

getOption


Description: Get client option.

Parameters

parameter name

Return value

Parameter value.

Example
// return Redis::SERIALIZER_NONE, Redis::SERIALIZER_PHP, 
//        Redis::SERIALIZER_IGBINARY, Redis::SERIALIZER_MSGPACK or Redis::SERIALIZER_JSON
$redis->getOption(Redis::OPT_SERIALIZER);

ping


Description: Check the current connection status.

Prototype
$redis->ping([string $message]);
Return value

Mixed: This method returns TRUE on success, or the passed string if called with an argument.

Example
/* When called without an argument, PING returns `TRUE` */
$redis->ping();

/* If passed an argument, that argument is returned.  Here 'hello' will be returned */
$redis->ping('hello');

Note: Prior to PhpRedis 5.0.0 this command simply returned the string +PONG.

echo


Description: Sends a string to Redis, which replies with the same string

Parameters

STRING: The message to send.

Return value

STRING: the same message.

Retry and backoff

  1. Maximum retries
  2. Backoff algorithms

Maximum retries

You can set and get the maximum retries upon connection issues using the OPT_MAX_RETRIES option. Note that this is the number of retries, meaning if you set this option to n, there will be a maximum n+1 attemps overall. Defaults to 10.

Example
$redis->setOption(Redis::OPT_MAX_RETRIES, 5);
$redis->getOption(Redis::OPT_MAX_RETRIES);

Backoff algorithms

You can set the backoff algorithm using the Redis::OPT_BACKOFF_ALGORITHM option and choose among the following algorithms described in this blog post by Marc Brooker from AWS: Exponential Backoff And Jitter:

  • Default: Redis::BACKOFF_ALGORITHM_DEFAULT
  • Decorrelated jitter: Redis::BACKOFF_ALGORITHM_DECORRELATED_JITTER
  • Full jitter: Redis::BACKOFF_ALGORITHM_FULL_JITTER
  • Equal jitter: Redis::BACKOFF_ALGORITHM_EQUAL_JITTER
  • Exponential: Redis::BACKOFF_ALGORITHM_EXPONENTIAL
  • Uniform: Redis::BACKOFF_ALGORITHM_UNIFORM
  • Constant: Redis::BACKOFF_ALGORITHM_CONSTANT

These algorithms depend on the base and cap parameters, both in milliseconds, which you can set using the Redis::OPT_BACKOFF_BASE and Redis::OPT_BACKOFF_CAP options, respectively.

Example
$redis->setOption(Redis::OPT_BACKOFF_ALGORITHM, Redis::BACKOFF_ALGORITHM_DECORRELATED_JITTER);
$redis->setOption(Redis::OPT_BACKOFF_BASE, 500); // base for backoff computation: 500ms
$redis->setOption(Redis::OPT_BACKOFF_CAP, 750); // backoff time capped at 750ms

Server

  1. acl - Manage Redis ACLs
  2. bgRewriteAOF - Asynchronously rewrite the append-only file
  3. bgSave - Asynchronously save the dataset to disk (in background)
  4. config - Get or Set the Redis server configuration parameters
  5. dbSize - Return the number of keys in selected database
  6. flushAll - Remove all keys from all databases
  7. flushDb - Remove all keys from the current database
  8. info - Get information and statistics about the server
  9. lastSave - Get the timestamp of the last disk save
  10. resetStat - Reset the stats returned by info method.
  11. save - Synchronously save the dataset to disk (wait to complete)
  12. slaveOf - Make the server a slave of another instance, or promote it to master
  13. time - Return the current server time
  14. slowLog - Access the Redis slowLog entries

acl


Description: Execute the Redis ACL command.

Parameters

variable: Minumum of one argument for Redis and two for RedisCluster.

Example
$redis->acl('USERS'); /* Get a list of users */
$redis->acl('LOG');   /* See log of Redis' ACL subsystem */

Note: In order to user the ACL command you must be communicating with Redis >= 6.0 and be logged into an account that has access to administration commands such as ACL. Please reference this tutorial for an overview of Redis 6 ACLs and the redis command reference for every ACL subcommand.

Note: If you are connecting to Redis server >= 4.0.0 you can remove a key with the unlink method in the exact same way you would use del. The Redis unlink command is non-blocking and will perform the actual deletion asynchronously.

bgRewriteAOF


Description: Start the background rewrite of AOF (Append-Only File)

Parameters

None.

Return value

BOOL: TRUE in case of success, FALSE in case of failure.

Example
$redis->bgRewriteAOF();

bgSave


Description: Asynchronously save the dataset to disk (in background)

Parameters

None.

Return value

BOOL: TRUE in case of success, FALSE in case of failure. If a save is already running, this command will fail and return FALSE.

Example
$redis->bgSave();

config


Description: Get or Set the Redis server configuration parameters.

Parameters

operation (string) either GET or SET
key string for SET, glob-pattern for GET. See http://redis.io/commands/config-get for examples.
value optional string (only for SET)

Return value

Associative array for GET, key -> value
bool for SET

Examples
$redis->config("GET", "*max-*-entries*");
$redis->config("SET", "dir", "/var/run/redis/dumps/");

dbSize


Description: Return the number of keys in selected database.

Parameters

None.

Return value

INTEGER: DB size, in number of keys.

Example
$count = $redis->dbSize();
echo "Redis has $count keys\n";

flushAll


Description: Remove all keys from all databases.

Parameters

async (bool) requires server version 4.0.0 or greater

Return value

BOOL: Always TRUE.

Example
$redis->flushAll();

flushDb


Description: Remove all keys from the current database.

Parameters

async (bool) requires server version 4.0.0 or greater

Return value

BOOL: Always TRUE.

Example
$redis->flushDb();

info


Description: Get information and statistics about the server

Returns an associative array that provides information about the server. Passing no arguments to INFO will call the standard REDIS INFO command, which returns information such as the following:

  • redis_version
  • arch_bits
  • uptime_in_seconds
  • uptime_in_days
  • connected_clients
  • connected_slaves
  • used_memory
  • changes_since_last_save
  • bgsave_in_progress
  • last_save_time
  • total_connections_received
  • total_commands_processed
  • role

You can pass a variety of options to INFO (per the Redis documentation), which will modify what is returned.

Parameters

option: The option to provide redis (e.g. "COMMANDSTATS", "CPU")

Example
$redis->info(); /* standard redis INFO command */
$redis->info("COMMANDSTATS"); /* Information on the commands that have been run (>=2.6 only)
$redis->info("CPU"); /* just CPU information from Redis INFO */

lastSave


Description: Returns the timestamp of the last disk save.

Parameters

None.

Return value

INT: timestamp.

Example
$redis->lastSave();

resetStat


Description: Reset the stats returned by info method.

These are the counters that are reset:

  • Keyspace hits
  • Keyspace misses
  • Number of commands processed
  • Number of connections received
  • Number of expired keys
Parameters

None.

Return value

BOOL: TRUE in case of success, FALSE in case of failure.

Example
$redis->resetStat();

save


Description: Synchronously save the dataset to disk (wait to complete)

Parameters

None.

Return value

BOOL: TRUE in case of success, FALSE in case of failure. If a save is already running, this command will fail and return FALSE.

Example
$redis->save();

slaveOf


Description: Changes the slave status

Parameters

Either host (string) and port (int), or no parameter to stop being a slave.

Return value

BOOL: TRUE in case of success, FALSE in case of failure.

Example
$redis->slaveOf('10.0.1.7', 6379);
/* ... */
$redis->slaveOf();

time


Description: Return the current server time.

Parameters

(none)

Return value

If successful, the time will come back as an associative array with element zero being the unix timestamp, and element one being microseconds.

Examples
$redis->time();

slowLog


Description: Access the Redis slowLog

Parameters

Operation (string): This can be either GET, LEN, or RESET
Length (integer), optional: If executing a SLOWLOG GET command, you can pass an optional length.

Return value

The return value of SLOWLOG will depend on which operation was performed. SLOWLOG GET: Array of slowLog entries, as provided by Redis SLOGLOG LEN: Integer, the length of the slowLog SLOWLOG RESET: Boolean, depending on success

Examples
// Get ten slowLog entries
$redis->slowLog('get', 10);
// Get the default number of slowLog entries

$redis->slowLog('get');
// Reset our slowLog
$redis->slowLog('reset');

// Retrieve slowLog length
$redis->slowLog('len');

Keys and Strings

Strings


  • append - Append a value to a key
  • bitCount - Count set bits in a string
  • bitOp - Perform bitwise operations between strings
  • decr, decrBy - Decrement the value of a key
  • get - Get the value of a key
  • getBit - Returns the bit value at offset in the string value stored at key
  • getRange - Get a substring of the string stored at a key
  • getSet - Set the string value of a key and return its old value
  • incr, incrBy - Increment the value of a key
  • incrByFloat - Increment the float value of a key by the given amount
  • mGet, getMultiple - Get the values of all the given keys
  • mSet, mSetNX - Set multiple keys to multiple values
  • set - Set the string value of a key
  • setBit - Sets or clears the bit at offset in the string value stored at key
  • setEx, pSetEx - Set the value and expiration of a key
  • setNx - Set the value of a key, only if the key does not exist
  • setRange - Overwrite part of a string at key starting at the specified offset
  • strLen - Get the length of the value stored in a key

Keys


  • del, delete, unlink - Delete a key
  • dump - Return a serialized version of the value stored at the specified key.
  • exists - Determine if a key exists
  • expire, setTimeout, pexpire - Set a key's time to live in seconds
  • expireAt, pexpireAt - Set the expiration for a key as a UNIX timestamp
  • keys, getKeys - Find all keys matching the given pattern
  • scan - Scan for keys in the keyspace (Redis >= 2.8.0)
  • migrate - Atomically transfer a key from a Redis instance to another one
  • move - Move a key to another database
  • object - Inspect the internals of Redis objects
  • persist - Remove the expiration from a key
  • randomKey - Return a random key from the keyspace
  • rename, renameKey - Rename a key
  • renameNx - Rename a key, only if the new key does not exist
  • type - Determine the type stored at key
  • sort - Sort the elements in a list, set or sorted set
  • ttl, pttl - Get the time to live for a key
  • restore - Create a key using the provided serialized value, previously obtained with dump.

get


Description: Get the value related to the specified key

Parameters

key

Return value

String or Bool: If key didn't exist, FALSE is returned. Otherwise, the value related to this key is returned.

Examples
$redis->get('key');

set


Description: Set the string value in argument as value of the key. If you're using Redis >= 2.6.12, you can pass extended options as explained below

Parameters

Key
Value
Timeout or Options Array (optional). If you pass an integer, phpredis will redirect to SETEX, and will try to use Redis >= 2.6.12 extended options if you pass an array with valid values

Return value

Bool TRUE if the command is successful.

Examples
// Simple key -> value set
$redis->set('key', 'value');

// Will redirect, and actually make an SETEX call
$redis->set('key','value', 10);

// Will set the key, if it doesn't exist, with a ttl of 10 seconds
$redis->set('key', 'value', ['nx', 'ex'=>10]);

// Will set a key, if it does exist, with a ttl of 1000 milliseconds
$redis->set('key', 'value', ['xx', 'px'=>1000]);

setEx, pSetEx


Description: Set the string value in argument as value of the key, with a time to live. PSETEX uses a TTL in milliseconds.

Parameters

Key TTL Value

Return value

Bool TRUE if the command is successful.

Examples
$redis->setEx('key', 3600, 'value'); // sets key → value, with 1h TTL.
$redis->pSetEx('key', 100, 'value'); // sets key → value, with 0.1 sec TTL.

setNx


Description: Set the string value in argument as value of the key if the key doesn't already exist in the database.

Parameters

key value

Return value

Bool TRUE in case of success, FALSE in case of failure.

Examples
$redis->setNx('key', 'value'); /* return TRUE */
$redis->setNx('key', 'value'); /* return FALSE */

del, delete, unlink


Description: Remove specified keys.

Parameters

An array of keys, or an undefined number of parameters, each a key: key1 key2 key3 ... keyN

Note: If you are connecting to Redis server >= 4.0.0 you can remove a key with the unlink method in the exact same way you would use del. The Redis unlink command is non-blocking and will perform the actual deletion asynchronously.

Return value

Long Number of keys deleted.

Examples
$redis->set('key1', 'val1');
$redis->set('key2', 'val2');
$redis->set('key3', 'val3');
$redis->set('key4', 'val4');

$redis->del('key1', 'key2'); /* return 2 */
$redis->del(['key3', 'key4']); /* return 2 */

/* If using Redis >= 4.0.0 you can call unlink */
$redis->unlink('key1', 'key2');
$redis->unlink(['key1', 'key2']);

Note: delete is an alias for del and will be removed in future versions of phpredis.

exists


Description: Verify if the specified key exists.

Parameters

key

Return value

long: The number of keys tested that do exist.

Examples
$redis->set('key', 'value');
$redis->exists('key'); /* 1 */
$redis->exists('NonExistingKey'); /* 0 */

$redis->mset(['foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz']);
$redis->exists(['foo', 'bar', 'baz']); /* 3 */
$redis->exists('foo', 'bar', 'baz'); /* 3 */

Note: This function took a single argument and returned TRUE or FALSE in phpredis versions < 4.0.0.

incr, incrBy


Description: Increment the number stored at key by one. If the second argument is filled, it will be used as the integer value of the increment.

Parameters

key
value: value that will be added to key (only for incrBy)

Return value

INT the new value

Examples
$redis->incr('key1'); /* key1 didn't exists, set to 0 before the increment */
					  /* and now has the value 1  */

$redis->incr('key1'); /* 2 */
$redis->incr('key1'); /* 3 */
$redis->incr('key1'); /* 4 */

// Will redirect, and actually make an INCRBY call
$redis->incr('key1', 10);   /* 14 */

$redis->incrBy('key1', 10); /* 24 */

incrByFloat


Description: Increment the key with floating point precision.

Parameters

key
value: (float) value that will be added to the key

Return value

FLOAT the new value

Examples
$redis->incrByFloat('key1', 1.5); /* key1 didn't exist, so it will now be 1.5 */


$redis->incrByFloat('key1', 1.5); /* 3 */
$redis->incrByFloat('key1', -1.5); /* 1.5 */
$redis->incrByFloat('key1', 2.5); /* 4 */

decr, decrBy


Description: Decrement the number stored at key by one. If the second argument is filled, it will be used as the integer value of the decrement.

Parameters

key
value: value that will be subtracted to key (only for decrBy)

Return value

INT the new value

Examples
$redis->decr('key1'); /* key1 didn't exists, set to 0 before the increment */
					  /* and now has the value -1  */

$redis->decr('key1'); /* -2 */
$redis->decr('key1'); /* -3 */

// Will redirect, and actually make an DECRBY call
$redis->decr('key1', 10);   /* -13 */

$redis->decrBy('key1', 10); /* -23 */

mGet, getMultiple


Description: Get the values of all the specified keys. If one or more keys don't exist, the array will contain FALSE at the position of the key.

Parameters

Array: Array containing the list of the keys

Return value

Array: Array containing the values related to keys in argument

Examples
$redis->set('key1', 'value1');
$redis->set('key2', 'value2');
$redis->set('key3', 'value3');
$redis->mGet(['key1', 'key2', 'key3']); /* ['value1', 'value2', 'value3'];
$redis->mGet(['key0', 'key1', 'key5']); /* [`FALSE`, 'value1', `FALSE`];

Note: getMultiple is an alias for mGet and will be removed in future versions of phpredis.

getSet


Description: Sets a value and returns the previous entry at that key.

Parameters

Key: key

STRING: value

Return value

A string, the previous value located at this key.

Example
$redis->set('x', '42');
$exValue = $redis->getSet('x', 'lol');	// return '42', replaces x by 'lol'
$newValue = $redis->get('x')'		// return 'lol'

randomKey


Description: Returns a random key.

Parameters

None.

Return value

STRING: an existing key in redis.

Example
$key = $redis->randomKey();
$surprise = $redis->get($key);	// who knows what's in there.

move


Description: Moves a key to a different database.

Parameters

Key: key, the key to move.

INTEGER: dbindex, the database number to move the key to.

Return value

BOOL: TRUE in case of success, FALSE in case of failure.

Example
$redis->select(0);	// switch to DB 0
$redis->set('x', '42');	// write 42 to x
$redis->move('x', 1);	// move to DB 1
$redis->select(1);	// switch to DB 1
$redis->get('x');	// will return 42

rename, renameKey


Description: Renames a key.

Parameters

STRING: srckey, the key to rename.

STRING: dstkey, the new name for the key.

Return value

BOOL: TRUE in case of success, FALSE in case of failure.

Example
$redis->set('x', '42');
$redis->rename('x', 'y');
$redis->get('y'); 	// → 42
$redis->get('x'); 	// → `FALSE`

Note: renameKey is an alias for rename and will be removed in future versions of phpredis.

renameNx


Description: Same as rename, but will not replace a key if the destination already exists. This is the same behaviour as setNx.

expire, setTimeout, pexpire


Description: Sets an expiration date (a timeout) on an item. pexpire requires a TTL in milliseconds.

Parameters

Key: key. The key that will disappear.

Integer: ttl. The key's remaining Time To Live, in seconds.

Return value

BOOL: TRUE in case of success, FALSE in case of failure.

Example
$redis->set('x', '42');
$redis->expire('x', 3);	// x will disappear in 3 seconds.
sleep(5);				// wait 5 seconds
$redis->get('x'); 		// will return `FALSE`, as 'x' has expired.

Note: setTimeout is an alias for expire and will be removed in future versions of phpredis.

expireAt, pexpireAt


Description: Sets an expiration date (a timestamp) on an item. pexpireAt requires a timestamp in milliseconds.

Parameters

Key: key. The key that will disappear.

Integer: Unix timestamp. The key's date of death, in seconds from Epoch time.

Return value

BOOL: TRUE in case of success, FALSE in case of failure.

Example
$redis->set('x', '42');
$now = time(NULL); // current timestamp
$redis->expireAt('x', $now + 3);	// x will disappear in 3 seconds.
sleep(5);				// wait 5 seconds
$redis->get('x'); 		// will return `FALSE`, as 'x' has expired.

keys, getKeys


Description: Returns the keys that match a certain pattern.

Parameters

STRING: pattern, using '*' as a wildcard.

Return value

Array of STRING: The keys that match a certain pattern.

Example
$allKeys = $redis->keys('*');	// all keys will match this.
$keyWithUserPrefix = $redis->keys('user*');

Note: getKeys is an alias for keys and will be removed in future versions of phpredis.

scan


Description: Scan the keyspace for keys

Parameters

LONG (reference): Iterator, initialized to NULL STRING, Optional: Pattern to match LONG, Optional: Count of keys per iteration (only a suggestion to Redis)

Return value

Array, boolean: This function will return an array of keys or FALSE if Redis returned zero keys

Note: SCAN is a "directed node" command in RedisCluster

Example
/* Without enabling Redis::SCAN_RETRY (default condition) */
$it = NULL;
do {
    // Scan for some keys
    $arr_keys = $redis->scan($it);

    // Redis may return empty results, so protect against that
    if ($arr_keys !== FALSE) {
        foreach($arr_keys as $str_key) {
            echo "Here is a key: $str_key\n";
        }
    }
} while ($it > 0);
echo "No more keys to scan!\n";

/* With Redis::SCAN_RETRY enabled */
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
$it = NULL;

/* phpredis will retry the SCAN command if empty results are returned from the
   server, so no empty results check is required. */
while ($arr_keys = $redis->scan($it)) {
    foreach ($arr_keys as $str_key) {
        echo "Here is a key: $str_key\n";
    }
}
echo "No more keys to scan!\n";

object


Description: Describes the object pointed to by a key.

Parameters

The information to retrieve (string) and the key (string). Info can be one of the following:

  • "encoding"
  • "refcount"
  • "idletime"
Return value

STRING for "encoding", LONG for "refcount" and "idletime", FALSE if the key doesn't exist.

Example
$redis->object("encoding", "l"); // → ziplist
$redis->object("refcount", "l"); // → 1
$redis->object("idletime", "l"); // → 400 (in seconds, with a precision of 10 seconds).

type


Description: Returns the type of data pointed by a given key.

Parameters

Key: key

Return value

Depending on the type of the data pointed by the key, this method will return the following value:
string: Redis::REDIS_STRING
set: Redis::REDIS_SET
list: Redis::REDIS_LIST
zset: Redis::REDIS_ZSET
hash: Redis::REDIS_HASH
other: Redis::REDIS_NOT_FOUND

Example
$redis->type('key');

append


Description: Append specified string to the string stored in specified key.

Parameters

Key Value

Return value

INTEGER: Size of the value after the append

Example
$redis->set('key', 'value1');
$redis->append('key', 'value2'); /* 12 */
$redis->get('key'); /* 'value1value2' */

getRange


Description: Return a substring of a larger string

Parameters

key
start
end

Return value

STRING: the substring

Example
$redis->set('key', 'string value');
$redis->getRange('key', 0, 5); /* 'string' */
$redis->getRange('key', -5, -1); /* 'value' */

Note: substr is an alias for getRange and will be removed in future versions of phpredis.

setRange


Description: Changes a substring of a larger string.

Parameters

key offset value

Return value

STRING: the length of the string after it was modified.

Example
$redis->set('key', 'Hello world');
$redis->setRange('key', 6, "redis"); /* returns 11 */
$redis->get('key'); /* "Hello redis" */

strLen


Description: Get the length of a string value.

Parameters

key

Return value

INTEGER

Example
$redis->set('key', 'value');
$redis->strlen('key'); /* 5 */

getBit


Description: Return a single bit out of a larger string

Parameters

key
offset

Return value

LONG: the bit value (0 or 1)

Example
$redis->set('key', "\x7f"); // this is 0111 1111
$redis->getBit('key', 0); /* 0 */
$redis->getBit('key', 1); /* 1 */

setBit


Description: Changes a single bit of a string.

Parameters

key
offset
value: bool or int (1 or 0)

Return value

LONG: 0 or 1, the value of the bit before it was set.

Example
$redis->set('key', "*");	// ord("*") = 42 = 0x2f = "0010 1010"
$redis->setBit('key', 5, 1); /* returns 0 */
$redis->setBit('key', 7, 1); /* returns 0 */
$redis->get('key'); /* chr(0x2f) = "/" = b("0010 1111") */

bitOp


Description: Bitwise operation on multiple keys.

Parameters

operation: either "AND", "OR", "NOT", "XOR"
ret_key: return key
key1
key2...

Return value

LONG: The size of the string stored in the destination key.

bitCount


Description: Count bits in a string.

Parameters

key

Return value

LONG: The number of bits set to 1 in the value behind the input key.

sort


Description: Sort the elements in a list, set or sorted set.

Parameters

Key: key Options: [key => value, ...] - optional, with the following keys and values:

    'by' => 'some_pattern_*',
    'limit' => [0, 1],
    'get' => 'some_other_pattern_*' or an array of patterns,
    'sort' => 'asc' or 'desc',
    'alpha' => TRUE,
    'store' => 'external-key'
Return value

An array of values, or a number corresponding to the number of elements stored if that was used.

Example
$redis->del('s');
$redis->sAdd('s', 5);
$redis->sAdd('s', 4);
$redis->sAdd('s', 2);
$redis->sAdd('s', 1);
$redis->sAdd('s', 3);

var_dump($redis->sort('s')); // 1,2,3,4,5
var_dump($redis->sort('s', ['sort' => 'desc'])); // 5,4,3,2,1
var_dump($redis->sort('s', ['sort' => 'desc', 'store' => 'out'])); // (int)5

ttl, pttl


Description: Returns the time to live left for a given key in seconds (ttl), or milliseconds (pttl).

Parameters

Key: key

Return value

LONG: The time to live in seconds. If the key has no ttl, -1 will be returned, and -2 if the key doesn't exist.

Example
$redis->ttl('key');

persist


Description: Remove the expiration timer from a key.

Parameters

Key: key

Return value

BOOL: TRUE if a timeout was removed, FALSE if the key didn’t exist or didn’t have an expiration timer.

Example
$redis->persist('key');

mSet, mSetNx


Description: Sets multiple key-value pairs in one atomic command. MSETNX only returns TRUE if all the keys were set (see SETNX).

Parameters

Pairs: [key => value, ...]

Return value

Bool TRUE in case of success, FALSE in case of failure.

Example
$redis->mSet(['key0' => 'value0', 'key1' => 'value1']);
var_dump($redis->get('key0'));
var_dump($redis->get('key1'));

Output:

string(6) "value0"
string(6) "value1"

dump


Description: Dump a key out of a redis database, the value of which can later be passed into redis using the RESTORE command. The data that comes out of DUMP is a binary representation of the key as Redis stores it.

Parameters

key string

Return value

The Redis encoded value of the key, or FALSE if the key doesn't exist

Examples
$redis->set('foo', 'bar');
$val = $redis->dump('foo'); // $val will be the Redis encoded key value

restore


Description: Restore a key from the result of a DUMP operation.

Parameters

key string. The key name
ttl integer. How long the key should live (if zero, no expire will be set on the key)
value string (binary). The Redis encoded key value (from DUMP)

Examples
$redis->set('foo', 'bar');
$val = $redis->dump('foo');
$redis->restore('bar', 0, $val); // The key 'bar', will now be equal to the key 'foo'

migrate


Description: Migrates a key to a different Redis instance.

Note:: Redis introduced migrating multiple keys in 3.0.6, so you must have at least that version in order to call migrate with an array of keys.

Parameters

host string. The destination host
port integer. The TCP port to connect to.
key(s) string or array.
destination-db integer. The target DB.
timeout integer. The maximum amount of time given to this transfer.
copy boolean, optional. Should we send the COPY flag to redis.
replace boolean, optional. Should we send the REPLACE flag to redis

Examples
$redis->migrate('backup', 6379, 'foo', 0, 3600);
$redis->migrate('backup', 6379, 'foo', 0, 3600, true, true); /* copy and replace */
$redis->migrate('backup', 6379, 'foo', 0, 3600, false, true); /* just REPLACE flag */

/* Migrate multiple keys (requires Redis >= 3.0.6)
$redis->migrate('backup', 6379, ['key1', 'key2', 'key3'], 0, 3600);

Hashes

  • hDel - Delete one or more hash fields
  • hExists - Determine if a hash field exists
  • hGet - Get the value of a hash field
  • hGetAll - Get all the fields and values in a hash
  • hIncrBy - Increment the integer value of a hash field by the given number
  • hIncrByFloat - Increment the float value of a hash field by the given amount
  • hKeys - Get all the fields in a hash
  • hLen - Get the number of fields in a hash
  • hMGet - Get the values of all the given hash fields
  • hMSet - Set multiple hash fields to multiple values
  • hSet - Set the string value of a hash field
  • hSetNx - Set the value of a hash field, only if the field does not exist
  • hVals - Get all the values in a hash
  • hScan - Scan a hash key for members
  • hStrLen - Get the string length of the value associated with field in the hash

hSet


Description: Adds a value to the hash stored at key.

Parameters

key
hashKey
value

Return value

LONG 1 if value didn't exist and was added successfully, 0 if the value was already present and was replaced, FALSE if there was an error.

Example
$redis->del('h')
$redis->hSet('h', 'key1', 'hello'); /* 1, 'key1' => 'hello' in the hash at "h" */
$redis->hGet('h', 'key1'); /* returns "hello" */

$redis->hSet('h', 'key1', 'plop'); /* 0, value was replaced. */
$redis->hGet('h', 'key1'); /* returns "plop" */

hSetNx


Description: Adds a value to the hash stored at key only if this field isn't already in the hash.

Return value

BOOL TRUE if the field was set, FALSE if it was already present.

Example
$redis->del('h')
$redis->hSetNx('h', 'key1', 'hello'); /* TRUE, 'key1' => 'hello' in the hash at "h" */
$redis->hSetNx('h', 'key1', 'world'); /* FALSE, 'key1' => 'hello' in the hash at "h". No change since the field wasn't replaced. */

hGet


Description: Gets a value from the hash stored at key. If the hash table doesn't exist, or the key doesn't exist, FALSE is returned.

Parameters

key
hashKey

Return value

STRING The value, if the command executed successfully
BOOL FALSE in case of failure

hLen


Description: Returns the length of a hash, in number of items

Parameters

key

Return value

LONG the number of items in a hash, FALSE if the key doesn't exist or isn't a hash.

Example
$redis->del('h')
$redis->hSet('h', 'key1', 'hello');
$redis->hSet('h', 'key2', 'plop');
$redis->hLen('h'); /* returns 2 */

hDel


Description: Removes a value from the hash stored at key. If the hash table doesn't exist, or the key doesn't exist, FALSE is returned.

Parameters

key
hashKey1
hashKey2
...

Return value

LONG the number of deleted keys, 0 if the key doesn't exist, FALSE if the key isn't a hash.

hKeys


Description: Returns the keys in a hash, as an array of strings.

Parameters

Key: key

Return value

An array of elements, the keys of the hash. This works like PHP's array_keys().

Example
$redis->del('h');
$redis->hSet('h', 'a', 'x');
$redis->hSet('h', 'b', 'y');
$redis->hSet('h', 'c', 'z');
$redis->hSet('h', 'd', 't');
var_dump($redis->hKeys('h'));

Output:

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
}

The order is random and corresponds to redis' own internal representation of the set structure.

hVals


Description: Returns the values in a hash, as an array of strings.

Parameters

Key: key

Return value

An array of elements, the values of the hash. This works like PHP's array_values().

Example
$redis->del('h');
$redis->hSet('h', 'a', 'x');
$redis->hSet('h', 'b', 'y');
$redis->hSet('h', 'c', 'z');
$redis->hSet('h', 'd', 't');
var_dump($redis->hVals('h'));

Output:

array(4) {
  [0]=>
  string(1) "x"
  [1]=>
  string(1) "y"
  [2]=>
  string(1) "z"
  [3]=>
  string(1) "t"
}

The order is random and corresponds to redis' own internal representation of the set structure.

hGetAll


Description: Returns the whole hash, as an array of strings indexed by strings.

Parameters

Key: key

Return value

An array of elements, the contents of the hash.

Example
$redis->del('h');
$redis->hSet('h', 'a', 'x');
$redis->hSet('h', 'b', 'y');
$redis->hSet('h', 'c', 'z');
$redis->hSet('h', 'd', 't');
var_dump($redis->hGetAll('h'));

Output:

array(4) {
  ["a"]=>
  string(1) "x"
  ["b"]=>
  string(1) "y"
  ["c"]=>
  string(1) "z"
  ["d"]=>
  string(1) "t"
}

The order is random and corresponds to redis' own internal representation of the set structure.

hExists


Description: Verify if the specified member exists in a key.

Parameters

key
memberKey

Return value

BOOL: If the member exists in the hash table, return TRUE, otherwise return FALSE.

Examples
$redis->hSet('h', 'a', 'x');
$redis->hExists('h', 'a'); /*  TRUE */
$redis->hExists('h', 'NonExistingKey'); /* FALSE */

hIncrBy


Description: Increments the value of a member from a hash by a given amount.

Parameters

key
member
value: (integer) value that will be added to the member's value

Return value

LONG the new value

Examples
$redis->del('h');
$redis->hIncrBy('h', 'x', 2); /* returns 2: h[x] = 2 now. */
$redis->hIncrBy('h', 'x', 1); /* h[x] ← 2 + 1. Returns 3 */

hIncrByFloat


Description: Increments the value of a hash member by the provided float value

Parameters

key
member
value: (float) value that will be added to the member's value

Return value

FLOAT the new value

Examples
$redis->del('h');
$redis->hIncrByFloat('h','x', 1.5); /* returns 1.5: h[x] = 1.5 now */
$redis->hIncrByFloat('h', 'x', 1.5); /* returns 3.0: h[x] = 3.0 now */
$redis->hIncrByFloat('h', 'x', -3.0); /* returns 0.0: h[x] = 0.0 now */

hMSet


Description: Fills in a whole hash. Non-string values are converted to string, using the standard (string) cast. NULL values are stored as empty strings.

Parameters

key
members: key → value array

Return value

BOOL

Examples
$redis->del('user:1');
$redis->hMSet('user:1', ['name' => 'Joe', 'salary' => 2000]);
$redis->hIncrBy('user:1', 'salary', 100); // Joe earns 100 more now.

hMGet


Description: Retrieve the values associated to the specified fields in the hash.

Parameters

key
memberKeys Array

Return value

Array An array of elements, the values of the specified fields in the hash, with the hash keys as array keys.

Examples
$redis->del('h');
$redis->hSet('h', 'field1', 'value1');
$redis->hSet('h', 'field2', 'value2');
$redis->hMGet('h', ['field1', 'field2']); /* returns ['field1' => 'value1', 'field2' => 'value2'] */

hScan


Description: Scan a HASH value for members, with an optional pattern and count

Parameters

key: String
iterator: Long (reference)
pattern: Optional pattern to match against
count: How many keys to return in a go (only a suggestion to Redis)

Return value

Array An array of members that match our pattern

Examples
$it = NULL;
/* Don't ever return an empty array until we're done iterating */
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
while($arr_keys = $redis->hScan('hash', $it)) {
    foreach($arr_keys as $str_field => $str_value) {
        echo "$str_field => $str_value\n"; /* Print the hash member and value */
    }
}

hStrLen


Description: Get the string length of the value associated with field in the hash stored at key.

Parameters

key: String
field: String

Return value

LONG the string length of the value associated with field, or zero when field is not present in the hash or key does not exist at all.

Lists

  • blPop, brPop - Remove and get the first/last element in a list
  • bRPopLPush - Pop a value from a list, push it to another list and return it
  • lIndex, lGet - Get an element from a list by its index
  • lInsert - Insert an element before or after another element in a list
  • lLen, lSize - Get the length/size of a list
  • lPop - Remove and get the first element in a list
  • lPush - Prepend one or multiple values to a list
  • lPushx - Prepend a value to a list, only if the list exists
  • lRange, lGetRange - Get a range of elements from a list
  • lRem, lRemove - Remove elements from a list
  • lSet - Set the value of an element in a list by its index
  • lTrim, listTrim - Trim a list to the specified range
  • rPop - Remove and get the last element in a list
  • rPopLPush - Remove the last element in a list, append it to another list and return it (redis >= 1.1)
  • rPush - Append one or multiple values to a list
  • rPushX - Append a value to a list, only if the list exists

blPop, brPop


Description: Is a blocking lPop(rPop) primitive. If at least one of the lists contains at least one element, the element will be popped from the head of the list and returned to the caller. If all the list identified by the keys passed in arguments are empty, blPop will block during the specified timeout until an element is pushed to one of those lists. This element will be popped.

Parameters

ARRAY Array containing the keys of the lists
INTEGER Timeout
Or
STRING Key1
STRING Key2
STRING Key3
...
STRING Keyn
INTEGER Timeout

Return value

ARRAY ['listName', 'element']

Example
/* Non blocking feature */
$redis->lPush('key1', 'A');
$redis->del('key2');

$redis->blPop('key1', 'key2', 10); /* ['key1', 'A'] */
/* OR */
$redis->blPop(['key1', 'key2'], 10); /* ['key1', 'A'] */

$redis->brPop('key1', 'key2', 10); /* ['key1', 'A'] */
/* OR */
$redis->brPop(['key1', 'key2'], 10); /* ['key1', 'A'] */

/* Blocking feature */

/* process 1 */
$redis->del('key1');
$redis->blPop('key1', 10);
/* blocking for 10 seconds */

/* process 2 */
$redis->lPush('key1', 'A');

/* process 1 */
/* ['key1', 'A'] is returned*/

bRPopLPush


Description: A blocking version of rPopLPush, with an integral timeout in the third parameter.

Parameters

Key: srckey
Key: dstkey
Long: timeout

Return value

STRING The element that was moved in case of success, FALSE in case of timeout.

lIndex, lGet


Description: Return the specified element of the list stored at the specified key.

0 the first element, 1 the second ...
-1 the last element, -2 the penultimate ...

Return FALSE in case of a bad index or a key that doesn't point to a list.

Parameters

key
index

Return value

String the element at this index
Bool FALSE if the key identifies a non-string data type, or no value corresponds to this index in the list Key.

Example
$redis->rPush('key1', 'A');
$redis->rPush('key1', 'B');
$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */
$redis->lindex('key1', 0); /* 'A' */
$redis->lindex('key1', -1); /* 'C' */
$redis->lindex('key1', 10); /* `FALSE` */

Note: lGet is an alias for lIndex and will be removed in future versions of phpredis.

lInsert


Description: Insert value in the list before or after the pivot value.

The parameter options specify the position of the insert (before or after). If the list didn't exists, or the pivot didn't exists, the value is not inserted.

Parameters

key
position Redis::BEFORE | Redis::AFTER
pivot
value

Return value

The number of the elements in the list, -1 if the pivot didn't exists.

Example
$redis->del('key1');
$redis->lInsert('key1', Redis::AFTER, 'A', 'X'); /* 0 */

$redis->lPush('key1', 'A');
$redis->lPush('key1', 'B');
$redis->lPush('key1', 'C');

$redis->lInsert('key1', Redis::BEFORE, 'C', 'X'); /* 4 */
$redis->lRange('key1', 0, -1); /* ['A', 'B', 'X', 'C'] */

$redis->lInsert('key1', Redis::AFTER, 'C', 'Y'); /* 5 */
$redis->lRange('key1', 0, -1); /* ['A', 'B', 'X', 'C', 'Y'] */

$redis->lInsert('key1', Redis::AFTER, 'W', 'value'); /* -1 */

lPop


Description: Return and remove the first element of the list.

Parameters

key

Return value

STRING if command executed successfully
BOOL FALSE in case of failure (empty list)