search
HomeBackend DevelopmentPHP TutorialCollection of some common functions in PHP_PHP tutorial

Collection of some common functions in PHP_PHP tutorial

Jul 13, 2016 am 09:52 AM
phpmainfunctionCommonly usedcollectarticletime

Collection of some common functions in PHP

This article mainly introduces the collection of some common functions in PHP. This article collects some time and date, output printing, and commonly used string functions. , commonly used array methods, friends in need can refer to it

 ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

//================================Time and date============ ===================

//y returns the last two digits of the year, the four-digit number of year Y, the number of month m, and the English month of M. d number of the month, D day of the week in English

$date=date("Y-m-d");

$date=date("Y-m-d H:i:s");//with hours, minutes and seconds

//include,include_once.require,require_once

//require("file.php") Before the PHP program is executed, the file specified by require will be read in. If an error occurs, it will be fatal.

//include("file.php") can be placed anywhere in the PHP program. The file specified by include will not be read until the PHP program is executed. If an error occurs,

will be prompted.

//================================Output printing============ ===================

//sprintf("%d","3.2") ;//Only formatting, returns the formatted string, no output.

//printf("%d","3.2") ;//Formatting and outputting

//print("3.2") ;//Only output

//echo "nihao","aa";//Can output multiple strings

//print_r(array("a","b","c"));//Display the key values ​​and elements of the array in sequence

//============================== Commonly used string functions========== =====================

//Get the length of the string, how many characters there are, spaces are also counted

$str=" sdaf sd ";

$len=strlen($str);

//Use the string in the first parameter to connect each element in the subsequent array and return a string.

$str=implode("-",array("a","b","c"));

//String splitting method, returns an array, uses the characters in the first parameter to split the following string, intercepts before, after, and between the specified characters. If the specified character is at the beginning or end, the beginning of the array returned Or the ending element is an empty string

//If it is not divided into strings, a null value will be returned to the corresponding element of the array. The last limit returns the length of the array. If there is no limit, it will continue to be divided.

$array=explode("a","asddad addsadassd dasdadfsdfasdaaa",4);

//print_r($array);

//Remove the leading spaces on the left side of the string and return

//If there is a second parameter, the leading spaces on the left will be removed instead of the string in the second parameter

$str=ltrim("a asd ","a");

//Remove spaces at the beginning of the right side of the string

$str=rtrim(" asd ");

//Remove the strings starting with the second parameter on both sides of the first string. If there is no second parameter, the leading spaces on both sides of the string will be removed by default

$str=trim(" sdsdfas ","a");

//How long (how many) characters are taken starting from the specified position in the first parameter of the string, and the first character position in the string is calculated from 0.

//If the second parameter is negative, the length of the string will be taken starting from the last number at the end of the string. The last character at the end counts -1, and the interception direction is always from left to right

$str=substr("abcdefgh",0,4);

//Replace the first parameter string of the third parameter with the second parameter string

$str=str_replace("a","","abcabcAbca");

//Same usage as str_replace, except case-insensitive

//$str=str_ireplace("a"," ","abcabcAbca");

//Returns a string in which the characters in the string in brackets are all uppercase

$str=strtoupper("sdaf");

//Change the first string in the brackets to uppercase and return

$str=ucfirst("asdf");

//Use echo, etc. to print the string in the brackets on the web page, and the string in the brackets will be printed out as it is, including the label character

$str=htmlentities("
");

//Return the number of times the second parameter string appears in the first string

$int=substr_count("abcdeabcdeablkabd","ab");

//Returns the position where the second string appears for the first time in the first string. The first character position is counted as 0

$int=strpos("asagaab","ab");

//Returns the position where the second string last appears in the first string, and the first character position is counted as 0

$int=strrpos("asagaabadfab","ab");

//Intercept and return the string string from the first occurrence of parameter two to the last character of parameter one from left to right in parameter one

$str=strstr("sdafsdgaababdsfgs","ab");

//Intercept and return the string string from the last occurrence of parameter two to the last character of parameter one from left to right in parameter one

$str=strrchr("sdafsdgaababdsfgs","ab");

//Add ""

before each character in parameter two before the same character in parameter one

$str=addcslashes("abcdefghijklmn","akd");

// Fill the string of parameter one to the length specified by parameter two (number of single characters). Parameter three is the specified filled string, do not write the default space

//Parameter four filling position, 0 is filled at the beginning of the left side of parameter one, 1 is filled at the beginning of the right side, and 2 is filled at the beginning of both sides. If not written,

will be padded at the beginning on the right by default.

$str=str_pad("abcdefgh",10,"at",0);

//Compare the Asker code values ​​of the corresponding characters in the two strings in turn. If the first pair is different, if the first pair is greater than the second parameter, 1 will be returned. Otherwise, -1 will be returned. If the two strings are exactly the same, 0 will be returned.

$int1=strcmp("b","a");

//Returns the formatted number format of the first parameter. The second parameter is to retain a few decimal places. The third parameter is to replace the decimal point with parameter three. The fourth parameter is what is used for each three digits of the integer part. Character segmentation

//If the last three parameters are not written, the decimal part will be removed by default, and the integer will be separated by commas every three digits. Parameter three and parameter four must exist at the same time

$str=number_format(1231233.1415,2,"d","a");

//============================== Commonly used array methods =========== ====================

$arr=array("k0"=>"a","k1"=>"b","k2"=>"c");

//Return the number of array elements

$int=count($arr);

//Determine whether there is a first parameter element in the array element of the second parameter

$bool=in_array("b",$arr);

//Returns a new array composed of all the key values ​​​​of the array in brackets. The original array does not change

$array=array_keys($arr);

//Determine whether the array of the second parameter contains the key value of the first parameter and return true or false

$bool=array_key_exists("k1",$arr);

//Returns a new array composed of all element values ​​in the original array. The key values ​​increase from 0 and the original array remains unchanged

$array=array_values($arr);

//Return the key value pointed to by the current array pointer

$key=key($arr);

//Return the element value pointed to by the current array pointer

$value=current($arr);

//Return the array consisting of the key value and element value of the element pointed by the current array pointer, and then push the pointer to the next position. Finally, the pointer points to an empty element and return empty

//There are four element values ​​corresponding to fixed key values ​​in the returned array, which are the key value and element value of the returned element, among which 0, 'key' key value corresponds to the returned element key value, 1, 'value' The key values ​​correspond to the returned element values ​​

$array=each($arr);

//First push the array pointer to the next bit, and then return the element value pointed to after the pointer moves

$value=next($arr);

// Push the array pointer to the previous position, and then return the element value pointed to after the pointer moves

$value=prev($arr);

//Reset the array pointer to point to the first element and return the element value

$value=reset($arr);

//Point the array pointer to the last element and return the last element value

$value=end($arr);

//Append the parameters after the first parameter as elements to the end of the first parameter array, the index is calculated from the smallest unused value, and the subsequent array length is returned

$int=array_push($arr,"d","dfsd");

//Add all parameters after the first parameter array as elements to the beginning of the first parameter array. The key value is re-accumulated from the first element with 0. The original non-numeric key value remains unchanged. The sorting position of the elements remains unchanged, and the array length after returning is

$int=array_unshift($arr,"t1","t2");

//Return to extract the last element value from the end of the array, and remove the last element from the original array

$value=array_pop($arr);

//array_pop On the contrary, extract and return the first element value of the array, and remove the first element from the original array

$value=array_shift($arr);

//Let the first parameter array reach the length of the second parameter value, add the third parameter as an element to the end of the first parameter array, the index is calculated from the smallest unused value and returned, the original array No change

$array1=array_pad($arr,10,"t10");

//Returns a new array with excess duplicate elements removed from the original array, and the original array remains unchanged

$array=array_unique($array1);

//Break the original array key values ​​and sort them by the Asker code value of the element values ​​from small to large, and the index will be recalculated from the number 0

$int=sort($array);

//Contrary to sort, reorder the element value in descending order of Asko code value, and recalculate the index from 0

$int=rsort($array);

//Returns an array in which each element value in the first parameter array is paid as a key value to the second parameter array in turn. The length of the two arrays must be the same, and the original array does not change

$array=array_combine(array("a","b","c","d","e"),$arr);

//Merge the two arrays and return the original array unchanged

$array=array_merge($arr,array("a","b","c"));

//In the first parameter array, intercept the array key value element starting from the second parameter value position to the third parameter value length and return it. The first element position of the array is counted from 0

$array=array_slice($arr,2,1);

//The interception function is the same as array_slice(), except that the intercepted part is removed from the original array

$array=array_splice($arr,2,1);

// Take the first parameter as the first element, increment the value of parameter three each time, and then store it in the array as an element after incrementing until the value reaches the value of parameter two and save it in the array. and return this array

//Parameter one, parameter two can be a number or a single character. A single character is calculated according to the ASCO code value. If the third parameter is not written, it will increment by 1 each time by default

$array=range(3,9,2);

//Rearrange the correspondence between the original array elements and the corresponding key values ​​randomly and return true or false

$bool=shuffle($arr);

//Calculate the sum of all numeric element values ​​in the array

$int=array_sum(array("a",2,"cssf"));

// Split an array into new array blocks. Each element of the new array is an array. The number of elements in each element of the new array is determined by parameter two

//The third parameter determines whether the key value of the element retains the original key value and does not need to be written. true means retaining, and the default is false not retaining

$array=array_chunk(array("a"=>"a","b","c","d","e","f","g","h"),2 ,true);

//json_encode() converts the array into a JSON format string and returns

$arr = array('k1'=>'val1','k2'=>'val2','k3'=>array('v3','v4'));

echo $encode_str = json_encode($arr);

//json_decode() converts the JSON format string into an object that can be coerced into an array and returns it. When the keys and values ​​in the JSON format string need to be enclosed in quotes, double quotes must be used

$decode_arr = (array)json_decode($encode_str);

var_dump($decode_arr);

?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1006578.htmlTechArticleCollection of some common functions in PHP This article mainly introduces the collection of some common functions in PHP. This article collects Some time and date, output printing, common string functions, common arrays...
Statement
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
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

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.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

See all articles

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 Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment