search
HomeBackend DevelopmentPHP TutorialDetailed explanation of PHP basic function examples

Detailed explanation of PHP basic function examples

Mar 17, 2018 am 09:59 AM
phpExampleDetailed explanation

This article mainly shares with you detailed examples of PHP basic functions, hoping to help everyone.

1. Functions related to output:

l print(): similar to the content provided by echo output, returning 1

l print_r() Generally used to print arrays , does not print the type

l var_dump(): print the value of the data, also There are types

2. Functions related to time

l date(): Display date and time

            Example: date(“Y-m-dH:i:s”)

l time(): timestamp (number of seconds)

l microtime (): Return the timestamp and microseconds

l strtotime(): Parse the date and time string into a timestamp

3 , Mathematics related functions:

l max($v1,$v2,$v3…) Find the maximum value

l min($v1,$v2,$v3…) Find Minimum value

l rand() random number

l mt_rand() generates a better random number

l round(variable[,N]) Keep n small bits

l ceil() Round up

l floor() Round down

l pow(x,y) Find xY

l abs( )Absolute value

l sqrt(): Find the square root

4. Functions related to functions

l function_exists('function name' ) Determine whether the function exists

l func_get_arg(subscript) Get the parameters corresponding to the specified subscript

l func_get_args(): Get in the custom function All parameters (the return value is an array)

l func_num_args(): Get the number of parameters of the current custom function

5. String-related functions

Basic function strlen(): get the length of the stringmb_strlen($string variable name, character encoding)

l implode (connection method, array): connect into one String

l explode(split character, target string): becomes array

l str_split(string, character length): Split characters according to the specified length The string is obtained as an array

l trim(string[,specified character]): The default is to remove the spaces on both sides of the string

l ltrim(): Remove the

## on the left #l rtrim(): Remove the

l on the right

substr(string, starting position starts from 0 [, length])

l

strstr (string, matching characters): Starting from the specified position, intercepting to the end (can be used to remove the file suffix name)

l strtolower(): all lowercase

l strtoupper() : All uppercase

l ucfirst(): Capitalize the first letter

l strpos (string, matching character): Determine the position where the character appears in the target string (first time)

l strrpos (string, matching characters)

l str_replace (matching target, replacement content, string itself)

l printf/sprintf (output string has placeholder, Sequential placeholder content..)%d %s

l str_repeat(): Repeat a string n times

l str_shuffle(): Shuffle the string randomly

6. Array-related functions

Array sorting functions

l

sort(): Sort by the value of the elements in ascending order (subscript rearrangement)

l

rsort(): Sort by the value of the elements in descending order (subscript rearrangement)

l

asort(): Sort by the value of the elements in ascending order (subscripts retained)

l

arsort(): Sort by the value of the elements in descending order (subscripts reserved) Reserved)

l

ksort(): Array key name (subscript) in ascending order, (subscript reserved)

l

krsort() : Arrange in descending order by key name, (subscripts retained)

l

shuffle(): Randomly shuffle the array elements, and the array subscripts will be rearranged

l Sort: The default is ascending order, if r is descending order)

l Yesa: Just keep the index relationship

l has k: issorted by key name

Pointer

l

reset() resets the pointer and returns the array pointer to the first position

l end() Reset the pointer and point the array pointer to the last element

l next() Move the pointer down to get the value of the next element

l prev() Move the pointer up to get the value of the previous element                                                        Move the pointer)

l key(): Get the subscript value corresponding to the current pointer (without moving the pointer)

Array Others Function

l count(): Count the number of elements in the array

l array_push(): Add an element to the array (After the array)

l array_pop(): Take out an element from the array (After the array)

l array_shift(): From the array Remove an element from the array (in front of the array)

l array_unshift(): Add an element from the array (in front of the array)

l array_reverse( ): Array elements are reversed

l in_array(): Determine whether an element exists in the array

l array_keys(): Get an All subscripts of the array, return an index array

l array_values(): Get all the values ​​of an array, return an index array

l array_merge():Merge one or more arrays

array_merge($arr1,$arr2)

l array_splice():Remove part of the array and replace it with other values

$input

<span style="color:#0000BB;">= array(</span><span style="color:#007700;">"red"</span><span style="color:#DD0000;">, </span><span style="color:#007700;">"green"</span><span style="color:#DD0000;">, </span><span style="color:#007700;">"blue"</span><span style="color:#DD0000;">, </span>##"yellow"<span style="color:#007700;"></span>);<span style="color:#DD0000;"></span><span style="color:#007700;"></span>array_splice
(<span style="color:#0000BB;"></span> $input<span style="color:#007700;"></span>##, <span style="color:#0000BB;"></span>2<span style="color:#007700;"></span>);<span style="color:#0000BB;"></span><span style="color:#007700;">//$input is now array(“red”,”</span> green

”);<span style="color:#0000BB;"></span>l array_chunk():<span style="color:#0000BB;">Split an array into multiple ones</span>l

shuffle():

Shuffle the arrayl

range():

Create an array containing the specified range unitl

is_file():

Judge whether the given file name is a normal filel

define():

Define a constantl

defined():

Check whether a constant with a certain name existsl

ini_set( ):

Set a value for a configuration option ini_set

(<span style="color:#0000BB;"></span>'display_errors'<span style="color:#007700;"></span>, <span style="color:#DD0000;"></span>'1'<span style="color:#007700;"></span>);<span style="color:#DD0000;"></span> l basename():<span style="color:#007700;">Return the file name part of the path</span>l

is_array():

Detect whether the variable is an arrayl

list():

Assign the values ​​in the array to some variables

<span style="color:#0000BB;">$info </span><span style="color:#007700;">= array(</span><span style="color:#DD0000;">'coffee'</span> <span style="color:#007700;">, </span><span style="color:#DD0000;">'brown'</span><span style="color:#007700;">, </span><span style="color:#DD0000;">'caffeine'</span> <span style="color:#007700;">);</span>
<span style="color:#007700;">list(</span><span style="color:#0000BB;">$drink</span><span style="color:#007700;">, </span><span style="color:#0000BB;">$color</span>##, <span style="color:#007700;"></span> $power<span style="color:#0000BB;"></span>##) = <span style="color:#007700;"></span>$info<span style="color:#0000BB;"></span>;<span style="color:#007700;"></span>
echo <span style="color:#007700;"></span>"<span style="color:#DD0000;"></span>$drink<span style="color:#0000BB;"></span> is <span style="color:#DD0000;"></span>$color<span style="color:#0000BB;"></span> and <span style="color:#DD0000;"></span>$power<span style="color:#0000BB;"></span> makes it special.\n"<span style="color:#DD0000;"></span>;<span style="color:#007700;"></span>l

nl2br():

Insert HTML newline mark before all new lines in the stringl

array_rand():

Randomly take out one or more units from the arrayl

count ():

Calculate the number of units in the array or the number of attributes in the objectl

reset():

Point the internal pointer of the array to the first unitRelated recommendations:

Search performance test of PHP function

Sharing of some vulnerability collections of PHP function

Usage example of php function array_walk

The above is the detailed content of Detailed explanation of PHP basic function examples. 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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools