Home php教程 PHP开发 30 code examples of common methods for operating redis in PHP

30 code examples of common methods for operating redis in PHP

Nov 29, 2016 am 11:15 AM
php

This article mainly introduces 30 code examples of common methods for operating redis in PHP. This article actually has more than 30 methods, which can operate string type, list type and set type data. Friends in need can refer to it


redis There are a lot of operations. I used to see a relatively comprehensive blog, but I can’t find it now. After searching for a long time, I will summarize some examples of PHP processing redis. I personally think some examples are commonly used. The following examples are all based on the php-redis extension.

1, connect

Description: The instance is connected to a Redis.
Parameters: host: string, port: int
Return value: BOOL Successful return: TRUE; Failure return: FALSE

Example:

< ?php
$redis = new redis();
$result = $redis->connect('127.0.0.1', 6379);
var_dump($result); //Result: bool(true)
?>


2, set
Description: Set the value of key and value
Parameter: Key Value
Return value: BOOL Successful return: TRUE; Failure return: FALSE
Example:

$ redis = new redis();
$redis->connect('127.0.0.1', 6379);
$result = $redis->set('test',"11111111111");
var_dump($result) ; //Result: bool(true)
?>



3, get

Description: Get the value of the specified key
Parameter: key
Return value: string or BOOL If the key does not exist, then Return FALSE. Otherwise, return the value corresponding to the specified key.
Example:

$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$result = $redis->get(' test');
var_dump($result); //Result: string(11) "11111111111"
?>


4, delete


Description: Delete the specified key
Parameters: a key, Or an uncertain number of parameters, an array for each key: key1 key2 key3 ... keyN
Return value: number of items deleted
Example:

$redis = new redis();
$redis-> ;connect('127.0.0.1', 6379);
$redis->set('test',"1111111111111");
echo $redis->get('test'); //Result: 1111111111111
$ redis->delete('test');
var_dump($redis->get('test')); //Result: bool(false)
?>



5, setnx

Description: If the key does not exist in the database, set the key value parameter
Parameter: key value
Return value: BOOL Successful return: TRUE; Failure return: FALSE

Example:


$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('test',"1111111111111");
$redis->setnx( 'test',"22222222");
echo $redis->get('test'); //Result: 1111111111111
$redis->delete('test');
$redis->setnx(' test',"22222222");
echo $redis->get('test'); //Result: 22222222
?>


6, exists

Description: Verify whether the specified key exists
Parameter key
Return value: Bool Successful return: TRUE; Failure return: FALSE
Example:

$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('test',"1111111111111");
var_dump($redis->exists('test')); //Result: bool(true)
?>



7, incr

Description: Numeric increment to store the key value key.
Parameters: key value: The value that will be added to the key
Return value: INT the new value
Example:

$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('test',"123");
var_dump($redis-> ;incr("test")); //Result: int(124)
var_dump($redis->incr("test")); //Result: int(125)
?>


8, decr

Description: Store key value in numerical decrement.
Parameters: key value: the value that will be added to the key
Return value: INT the new value
Example:

$redis = new redis();
$redis->connect('127.0 .0.1', 6379);
$redis->set('test',"123");
var_dump($redis->decr("test")); //Result: int(122)
var_dump ($redis->decr("test")); //Result: int(121)
?>


9, getMultiple

Description: Get the values ​​of all specified keys. If one or more keys do not exist, the value of that key in the array is false
Parameters: Array of lists containing the values ​​of the keys
Return value: Returns an array containing the values ​​of all keys
Example:


$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('test1',"1");
$ redis->set('test2',"2");
$result = $redis->getMultiple(array('test1','test2'));
print_r($result); //Result: Array ( [0] => 1 [1] => 2 )
?>


10, lpush

Description: Add a string value from the head of the list. Create the list if the key does not exist. If the key exists and is not a list, return FALSE.
Parameters: key, value
Return value: Returns the array length on success, false on failure
Example:

$redis = new redis();
$redis->connect('127.0.0.1 ', 6379);
$redis->delete('test');
var_dump($redis->lpush("test","111")); //Result: int(1)
var_dump($ redis->lpush("test","222")); //Result: int(2)
?>


11, rpush

Description: Add a string value from the end of the list. Create the list if the key does not exist. If the key exists and is not a list, return FALSE.
Parameters: key, value
Return value: Returns the array length on success, false on failure
Example:

$redis = new redis();
$redis->connect('127.0.0.1 ', 6379);
$redis->delete('test');
var_dump($redis->lpush("test","111")); //Result: int(1)
var_dump($ redis->lpush("test","222")); //Result: int(2)
var_dump($redis->rpush("test","333")); //Result: int( 3)
var_dump($redis->rpush("test","444")); //Result: int(4)
?>


12, lpop

Description: Return and move Remove the first element of the list
Parameters: key
Return value: Return the value of the first element if successful, false if failed
Example:

$redis = new redis();
$ redis->connect('127.0.0.1', 6379);
$redis->delete('test');
$redis->lpush("test","111");
$redis-> ;lpush("test","222");
$redis->rpush("test","333");
$redis->rpush("test","444");
var_dump($ redis->lpop("test")); //Result: string(3) "222"
?>


13, lsize,llen

Description: The length of the returned list. If the list does not exist or is empty, the command returns 0. If the key is not a list, this command returns FALSE.
Parameter: Key
Return value: Returns the array length on success, false on failure
Example:

$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->delete('test');
$redis->lpush("test","111");
$redis->lpush("test","222");
$redis->rpush("test","333");
$redis->rpush("test","444");
var_dump($redis->lsize("test")); //Result: int(4)
?>


14, lget

Description: Returns the element specified by the specified key stored in the list. 0 first element, 1 second... -1 last element, -2 second last... Returns FALSE if the wrong index or key does not point to the list.
Parameter: key index
Return value: Return the value of the specified element if successful, false on failure
Example:


$redis = new redis();
$redis->connect('127.0 .0.1', 6379);
$redis->delete('test');
$redis->lpush("test","111");
$redis->lpush("test"," 222");
$redis->rpush("test","333");
$redis->rpush("test","444");
var_dump($redis->lget("test ",3)); //Result: string(3) "444"
?>


15, lset

Description: Assign a new value to the index specified in the list, if the index does not exist Return false.
Parameter: key index value
Return value: Return true if successful, false if failed
Example:

$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->delete('test');
$redis-> lpush("test","111");
$redis->lpush("test","222");
var_dump($redis->lget("test",1)); //Result: string(3) "111"
var_dump($redis->lset("test",1,"333")); //Result: bool(true)
var_dump($redis->lget("test" ,1)); //Result: string(3) "333"
?>


16, lgetrange

Description:
Returns the specified storage from start to end in the specified key list in this area Element, lGetRange(key, start, end). 0 for the first element, 1 for the second element... -1 for the last element, -2 for the penultimate element...
Parameters: key start end
Return value: Successfully returns the value found, failure is false
Example:

$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->delete('test');
$redis-> lpush("test","111");
$redis->lpush("test","222");
print_r($redis->lgetrange("test",0,-1)); / /Result: Array ( [0] => 222 [1] => 111 )
?>



17,lremove

Description: Remove count matches from the head of the list value. If count is zero, all matching elements are removed. If count is negative, the content is deleted from the end.
Parameter: key count value
Return value: Return the number of deleted items successfully, false on failure
Example:


$redis = new redis();
$redis->connect(' 127.0.0.1', 6379);
$redis->delete('test');
$redis->lpush('test','a');
$redis->lpush('test', 'b');
$redis->lpush('test','c');
$redis->rpush('test','a');
print_r($redis->lgetrange(' test', 0, -1)); //Result: Array ( [0] => c [1] => b [2] => a [3] => a )
var_dump($redis ->lremove('test','a',2)); //Result: int(2)
print_r($redis->lgetrange('test', 0, -1)); //Result: Array ( [0] => c [1] => b )
?>


18, sadd

Description: Add a value to a Key. If this value is already in this Key, return FALSE.
Parameter: key value
Return value: Return true on success, false on failure
Example:

$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->delete('test');
var_dump($redis->sadd('test','111')); //Result: bool(true)
var_dump($redis- >sadd('test','333')); //Result: bool(true)
print_r($redis->sort('test')); //Result: Array ( [0] => 111 [1] => 333 )
?>


19, sremove

Description: Delete the value specified in Key
Parameter: key member
Return value: true or false
Example:

$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->delete('test');
$redis- >sadd('test','111');
$redis->sadd('test','333');
$redis->sremove('test','111');
print_r( $redis->sort('test')); //Result: Array ([0] => 333)
?>


20,smove

Description: Move the value in Key1 Go to Key2
Parameter: srcKey dstKey member
Return value: true or false
Example

$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->delete('test');
$redis->delete('test1');
$redis->sadd('test','111');
$redis- >sadd('test','333');
$redis->sadd('test1','222');
$redis->sadd('test1','444');
$redis ->smove('test',"test1",'111');
print_r($redis->sort('test1')); //Result: Array ( [0] => 111 [1] => 222 [2] => 444 )
?>


21, scontains

Description: Checks whether the specified value exists in the collection.
Parameter: key value
Return value: true or false
Example:


$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->delete('test');
$redis-> sadd('test','111');
$redis->sadd('test','112');
$redis->sadd('test','113');
var_dump($redis ->scontains('test', '111')); //Result: bool(true)
?>


22,ssize

Description: Returns the number of stored values ​​in the collection
Parameters: key
Return value: The number of arrays is returned on success, 0 on failure
Example:


$redis = new redis();
$redis->connect('127.0.0.1', 6379 );
$redis->delete('test');
$redis->sadd('test','111');
$redis->sadd('test','112');
echo $redis->ssize('test'); //Result: 2
?>


23, spop

Description: Randomly remove and return a value in key
Parameter: key
Return value: Return the deleted value on success, false on failure
Example:

$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->delete('test');
$redis->sadd("test","111");
$redis->sadd("test","222");
$redis- >sadd("test","333");
var_dump($redis->spop("test")); //Result: string(3) "333"
?>


24,sinter

Description: Returns the intersection of all specified keys. If only a key is specified, this command generates members of the set. If a key does not exist, returns FALSE.
Parameters: key1, key2, keyN
Return value: Return array intersection on success, false on failure
Example:

$redis = new redis();
$redis->connect('127.0 .0.1', 6379);
$redis->delete('test');
$redis->sadd("test","111");
$redis->sadd("test"," 222");
$redis->sadd("test","333");
$redis->sadd("test1","111");
$redis->sadd("test1", "444");
var_dump($redis->sinter("test","test1")); //Result: array(1) { [0]=> string(3) "111" }
? >


25,sinterstore

Description: Execute the sInter command and store the result in the newly created variable.
Parameters:
Key: dstkey, the key to store the diff into.
Keys: key1, key2… keyN. key1..keyN are intersected as in sInter.
Return value: Return successfully, the number of intersections, false on failure
Example:

$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->delete('test');
$redis->sadd("test","111");
$redis->sadd("test","222");
$redis->sadd("test","333") ;
$redis->sadd("test1","111");
$redis->sadd("test1","444");
var_dump($redis->sinterstore('new'," test","test1")); //Result: int(1)
var_dump($redis->smembers('new')); //Result: array(1) { [0]=> string( 3) "111" }
?> Return the merged set, false on failure
Example:


$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis ->delete('test');
$redis->sadd("test","111");
$redis->sadd("test","222");
$redis-> sadd("test","333");
$redis->sadd("test1","111"); $redis->sadd("test1","444");

print_r($redis ->sunion("test","test1")); //Result: Array ( [0] => 111 [1] => 222 [2] => 333 [3] => 444 )
?>





27, sunionstore

Description: Execute the sunion command and store the results in the newly created variable.
Parameters:
Key: dstkey, the key to store the diff into.
Keys: key1, key2… keyN. key1..keyN are intersected as in sInter.
Return value: Return successfully, the number of intersections, false on failure
Example:


$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->delete('test');
$redis-> sadd("test","111");
$redis->sadd("test","222");
$redis->sadd("test","333");
$redis-> ;sadd("test1","111");
$redis->sadd("test1","444");
var_dump($redis->sinterstore('new',"test","test1" )); //Result: int(4)
print_r($redis->smembers('new')); //Result: Array ( [0] => 111 [1] => 222 [2] => 333 [3] => 444 )
?>


28,sdiff

Description: Returns results that exist in the first set and do not exist in all other sets
Parameters: Keys : key1, key2, …, keyN: Any number of keys corresponding to sets in redis.
Return value: Return array on success, false on failure
Example:


$redis = new redis() ;
$redis->connect('127.0.0.1', 6379);
$redis->delete('test');
$redis->sadd("test","111");
$ redis->sadd("test","222");
$redis->sadd("test","333");
$redis->sadd("test1","111");
$redis->sadd("test1","444");
print_r($redis->sdiff("test","test1")); //Result: Array ( [0] => 222 [ 1] => 333 )
?>


29,sdiffstore

Description: Execute the sdiff command and store the results in the newly created variable.
Parameters:
Key: dstkey, the key to store the diff into.
Keys: key1, key2, … , keyN: Any number of keys corresponding to sets in redis
Return value: Return a number on success, false on failure
Example:

$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->delete('test');
$redis ->sadd("test","111");
$redis->sadd("test","222");
$redis->sadd("test","333");
$ redis->sadd("test1","111");
$redis->sadd("test1","444");
var_dump($redis->sdiffstore('new',"test", "test1")); //Result: int(2)
print_r($redis->smembers('new')); //Result: Array ( [0] => 222 [1] => 333 )
?>


30,smembers, sgetmembers

Description:
Return the contents of the set
Parameters: Key: key
Return value: An array of elements, the contents of the set.
Example:

$redis = new redis();
$redis->connect('127.0.0.1', 6379);
$redis->delete('test');
$redis-> ;sadd("test","111");
$redis->sadd("test","222");
print_r($redis->smembers('test')); //Result: Array ( [0] => 111 [1] => 222 )
?>


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1280
29
C# Tutorial
1257
24
The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

Using Laravel: Streamlining Web Development with PHP Using Laravel: Streamlining Web Development with PHP Apr 19, 2025 am 12:18 AM

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

PHP and IIS: Making Them Work Together PHP and IIS: Making Them Work Together Apr 21, 2025 am 12:06 AM

Configuring and running PHP on IIS requires the following steps: 1) Download and install PHP, 2) Configuring IIS and adding FastCGI module, 3) Create and set up an application pool, 4) Create a website and bind to an application pool. Through these steps, you can easily deploy PHP applications on your Windows server and improve application stability and efficiency by configuring scaling and optimizing performance.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

See all articles