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

Is it necessary to memorize common functions in PHP?

Oct 29, 2019 pm 03:40 PM
php Commonly used functions

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 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
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles