Home  >  Article  >  Backend Development  >  Is it necessary to memorize common functions in PHP?

Is it necessary to memorize common functions in PHP?

angryTom
angryTomOriginal
2019-10-29 15:40:263325browse

Is it necessary to memorize common functions in PHP?

Is it necessary to memorize common functions in php

No need to memorize them. There are not many commonly used functions in PHP, they are all combinations of short words. You will naturally remember it after using it for a long time. If it is really difficult to remember, you can query it through the following form.

1. PHP system functions

## serialize()Serialize $arg, that is, convert it into text to save or transmit without losing its type and structure serialize(mixed $arg) unserialize() Deserialize $str and return the type and format information before serialization unserialize($str) getcwd()Get the directory where the script is currently running getcwd() basename()Return the Chinese part of the path basename($url) preg_match() Use $string to match the regular expression, and use $res to return the matching result as matching 1 or not matching 0 preg_match($string,regular expression,$res)

Function

Function Usage
var_dump() Print variable structure information, including type and value. The array will recursively expand the values ​​

var_dump ( $arg1...);

echo(): is a syntax structure Outputs one or more strings , you can use single quotes or double quotes without using (). Variables are output directly,

echo $arg1,$arg2...;

isset() Detects whether the variable is set and returns true when the value is not null, otherwise false isset ($args)
empty() Detect whether the variable is empty empty($args)
exit() Output a message and exit the current version exit('Exit successfully')
die() Output a message and stop the code execution die ('Code has stopped')
iconv() The character set is converted according to the specified encoding iconv(incharset,outcharset,$str)
uniqid() Get a unique ID (no parameters) or get a prefixed unique ID based on the current time microseconds (see parameters). uniqid([prefix name], [true])
gettype() Get the data type gettype($ args)
settype() Set the variable $arg to a certain data type settype($args,"[int][string] ...")

Binary, base conversion function

##Functiondecbin()decoct()dechex()bindec()##octdec()Octal ——> Decimaloctdec($num)hexdec()Hexadecimal ——> Decimalhexdec($num)base_convert()Any base conversion## The English of each base:
Function Usage
Decimal ——> Binary decbin($num)
Decimal ——> Octal decoct($num)
Decimal ——> Hexadecimal dechex($num)
Binary ——> Decimal bindec($num)
base_convert(the converted value, The base of the value, the base to be converted into)

## 10 Hexadecimal: hexadecimal

3. Constant function

Function

Function

Usagedefine()Define constants, the third parameter selects whether it is case-sensitive. define(constant name, constant value, [true])defined()Judge whether a constant exists define (constant name)get_defined_constants()Get predefined constantsget_defined_constant()

4. Judgment function

#FunctionFunctionUsageis_bool()Determine whether it is a Boolean typeis_bool()is_int()Determine whether it is an integeris_int()is_string()Determine whether it is a string is_string()##is_float()is_numeric()##is_null()Judge whether it is emptyis_null()is_array()Judge whether it is an arrayis_array( )is_dir()Judge whether it is a pathid_dir()5. String function
Determine whether it is a floating point type is_float()
Determine whether it is a number or a numeric string is_numeric()

##FunctionFunction returns string from $ ( $str Get the position (subscript) where $needle first appears in $str, no return false strpos($str,$needle) strrpos() Get the position (subscript) of the last occurrence of $needle in $str ), does not return false strrpos($str,$needle) substr() Intercepts the string $str from the $start position to $length strings substr($str,$start,$length) implode() Use to connect the arrays into Stringimplode(',',$arr)explode() is used to split the string into arraysexplode(',',$str) str_split()Split the string $str into an array, each unit length is 5 str_split($str,5) str_replace()Replace a with b in string $str str_replace(a ,b,$str) strtolower() Convert the string to lowercase strtolower($str) strtoupper() Convert string to uppercase strtoupper($str) ucfirst() Convert the first character of the string $str to uppercase ucfirst($str) unwords($str) trim($str) rtrim($str) strlen($str) substr_count($str,"$a") str_repeat($str,$num) strpad($str,$length,"0",STR_PAD_LEFT) strrev($str) rand(m,n) mt_rand(m,n) pow(m,n) number_format($n)
Usage strstr() is an alias of strchr()
$strneedle

The string starting from the first occurrence to the end. and is case-sensitive. If you don’t want to be case-sensitive, please use: stristr()

##strstr

, $needle ) strpos()

## unwords() Convert the string to uppercase Convert each word in $str to capitalize the first letter
trim() Remove the whitespace characters at both ends of the string and Other characters
rtrim() Remove blank characters and other characters on the right side of the string
strlen() Get the string length
substr_count() Count the number of occurrences of a string $a in string $str
str_repeat() Repeat output $str, the number of times is $num
strpad () Pad the left side of $str with 0 to make the length $length
strrev() Reverse the order of strings
rand() Take a random integer between m-n
mt_rand() Take a random integer between m-n and get the speed Faster than mt_rand()
pow() Take m raised to the nth power
number_format() Format a number with thousand separators

6. Array function

#FunctionFunctionUsageunset()unset($arr)/unset( $arr[n])array_values()Get all the values ​​in the array and re-establish the numeric subscriptarray_values($arr) array_keys()Get all key values ​​in the arrayarray_keys($arr) is_array()Judge whether it is an arrayis_array($arr)in_array()Judge whether the array $arr Contains a certain element $strin_array($str,$arr)count()Statistical array length/Statistical multi-dimensional array lengthcount($arr)/count($arr,1)range()Create an array of 1-9rang(1,9), range(a-z)array_merge()Connect multiple arrays into one arrayarray_merge($ arr,$brr…)array_rand() Randomly extract n units from the array, return the key value, and become a new array array_rand($arr,n)##shuffle()each()list(): Language structureAssign the values ​​in the array to some variablesarray_unshift()array_push()array_pop()array_key_exist()array_search( )array_flip()array_count_values()array_unique()sort()asort()maintain the index relationshiprsort()arsortnatsort()ksort()krsort()array_sum()key()current()next()##prev()Move the pointer in the array forward one positionprev($arr)reset()Reset the position of the pointer in the array (pointing to the one position)reset($arr)end()Move the pointer in the array to the last positionend($arr)7. Time function
Destroy the specified variable
Disorder the array shuffle($arr)
Returns the key/value pair of the current element in the array and automatically moves the array pointer forward one step each($arr)
list($a,$b,$c) =$arr
Insert one or more cells at the beginning of the array array_unshift($arr,$v1,$v2. ..)
Insert one or more cells at the end of the array array_push($arr,$v1,$v2… )
Remove the last element of the array and return array_pop($arr)
Determine whether key $k exists in the array array_key_exist($k,$arr)
Search for the given value $v in the array, and if successful, return the corresponding key name array_search($v,$arr)
Exchange the keys and values ​​of the array array_flip($arr)
Statistics The number of occurrences of all values ​​in the array array_count_values($arr)
Remove duplicate values ​​in the array array_unique($arr)
Sort the array in ascending order according to the size of the value sort($arr)
Arrange the array in ascending order according to the size of the value and asort($arr)
Arrange the array in descending order according to the size of the value and rearrange the index rsort($arr)
Arrange the array in descending order by value size, keeping the index arsort($arr)
Natural sorting (in line with people’s daily usage habits) natsort($arr)
Sort the array according to the key Arrange in descending order of size, retaining the association between key name and data ksort($arr)
Sort the array in descending order according to the size of the key Arrange, retaining the association of key names to data krsort($arr)
Sum all values ​​in the array array_sum($arr)
Get the position (key) of the traversal pointer in the array key($ arr)
Get the value of the pointer position current($arr)
Move the pointer in the array back one position next($arr)

FunctionFunctionUsageGet the current timestampGet the timestamp of the specified timeOutput the time $tmp in the specified formatParse the date and time description of any English text into a Unix timestamp
##time()
time() mktime()
mktime (hour, minute, second, month, Day, year) date()
date('Y-m-d H:i:s',$ tmp) strtotime()
strtotime("now")

8. Database functions

#FunctionFunctionFunctionmysql_connect()Link mysql databasemysql_connect($host,$user,$pwd)mysql_query()Send a MySQL statementmysql_query(sql statement)##mysql_fetch_assoc()mysql_fetch_array()mysql_fetch_row()mysql_select_db()##mysql_num_rows()Get the number of query result recordsmysql_num_rows (Query result)9. File operation function
Take out a row of data from the result set to form an associative array and return it, and continue to move the internal data pointer mysql_fetch_assoc($result)
Take out a row of data from the result set to form an array and return it, and continue to move the internal data pointer mysql_fetch_array($result, parameter)
Fetch a row of data from the result set to form an index array and return it, and continue to move the internal data pointer mysql_fetch_row($result)
Select database mysql_select_db(database name)

##fopen()Open a file or URL##fwrite( )Write content in the filefwrite("filename","content")fclose() Close the file or URLfclose("filename")file_put_contents()Write content in one stepfile_put_contents(" filename","content")file_get_contents()Read the content in one stepfile_get_contents("filename","content")fread()Read the file content of the specified lengthfread("filename", number of bytes)filesize()Get the file content length (number of bytes)filesize("filename")fgets()Read a linefgets($handle,length)file()Read the entire file into an arrayfile("filename")copy()Copy the file, the new file name is "newfile"copy( "filename","newfile")unlink($filename)filectime($filename)fileatime($filename)filemtime($ filename)feof($filename)json_encode($a)Decode JSON data into PHP data variablesWhen the parameter is true, return array
fopen("filename","mode")
##unlink() Delete file
filectime() Get the file creation time
fileatime() Get File last access time
filemtime() Get file modification time
feof() Determine whether the pointer reaches the end of the file
json_encode() Compile data into JSON data
json_decode()
json_decode($j,[false]/true)

10. Directory operation function

##Function

Function

Usagemkdir()Create a directory, if there is 0777, whether to create it recursivelymkdir("/path/to/my /dir", 0777);
##rmdir() Delete directory rmdir($DIR)
opendir() Open directory handle opendir($dir)
readdir() Read directory readdir($dir)
closedir() Close the directory closedir($dir)
rewinddir() Reset directory resources rewinddir($dir)
file_exists() Determine whether the file/directory exists file_exists($filename/$dir)
rename() Rename the file/directory rename($filename/$dir,$newname)
dirname() dirname($path) Return path The directory part in
basename() Returns the filename part in the path basename($path)
pathinfo() Get path information pathinfo($path, [options])

11. Class function

##FunctionFunctionFunction class_exists()Determine whether the class existsclass_exists($classname)interface_exists( )Determine whether the interface existsinterface_exists($name)##method_exists()##property_exists() Determine whether the attribute existsproperty($name)get_class()Get the class nameget_class()get_parent_class()Get the parent Class nameget_parent_class()get_class_methods()Get the methods in the classget_class_methods()get_class_vars()Returns an array consisting of the default attributes of the classget_class_vars()get_declared_class() Get the name of the defined classget_declared_class()__toString()Treat the object as a string Call __toString()__construct() Automatically call __construct()Automatically called when destroying the objectAutomatically called when cloning an objectAutomatically called when the object is called as a functionAutomatically called when assigning values ​​to inaccessible member propertiesAutomatically called when reading the value of an unreadable member attributeAutomatically called when isset() or empty() is used on inaccessible member attributesAutomatically call when using unset() on inaccessible member attributes Created for the class An aliasReturns an association containing the defined attributes and values ​​available for object ArrayReturns TRUE if the object belongs to this class or this class is the parent class of this objectIf the class to which object object belongs is a subclass of class class_name, return TRUE, otherwise Return FALSE. PHP Chinese website!
Determine whether the method exists method_exists($name)
## when calling New object #__destruct()
__destruct() __clone()
__clone() __invoke()
__invoke() __set()
__set() __get()
__get() __isset( )
__isset() __unset()
__unset() class_alias()
class_alias(original class, category name) get_object_vars()
get_object_vars() is_a()
is_a($obj,$classname) is_subclass_of()
is_subclass_of($obj,$classname)

##For more PHP related knowledge, please visit

The above is the detailed content of Is it necessary to memorize common functions in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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