search
HomeBackend DevelopmentPHP Tutorial不常见却非常有用的PHP函数

一个工作多年的php老程序员的总结,在php自带的函数库里面有很多不常见却有非常实用的函数,下面就分享10个不常见却非常有用的php函数。

1.sys_getloadavg()

sys_getloadavt()可以获得系统负载情况。该函数返回一个包含三个元素的数组,每个元素分别代表系统再过去的1、5和15分钟内的平均负载。 与其让服务器因负载过高而宕掉,不如在系统负载很高时主动die掉一个脚本,sys_getloadavg()就是用来帮你实现这个功能的。 不过很遗憾,该函数在windows下无效。

2.pack()

pack()能将md5()返回的32位16进制字符串转换为16位的二进制字符串,可以节省存储空间。

3.cal_days_in_month()

cal_days_in_month()能够返回指定月份共有多少天。

4._()

WordPress开发者经常能见到这个函数,还有_e()。这两个函数功能相同,与gettext()函数结合使用,能实现网站的多语言化。具体可参见PHP手册的相关部分介绍。

5.get_browser()

在发送页面前先看看用户的浏览器都能做些什么是不是挺好?

get_browser()能获得用户的浏览器类型,以及浏览器支持的功能,不过首先你需要一个php_browscap.ini文件,用来给函数做参考文件。要注意,该函数对浏览器功能的判断是基于该类浏览器的一般特性的。例如,如果用户关闭了浏览器对JavaScript的支持,函数无法得知这一点。但是在判断浏览器类型和OS平台方面,该函数还是很准确的。

6.debug_print_backtrace()

这是一个调试用的函数,能帮助你发现代码中的逻辑错误。要理解这个函数,还是直接看个例子吧:

<p><?php</p>$a=0;<br />function iterate(){<br />	global $a;<br />	if($a<10){<br />		recur();<br />	}<br />	echo $a.", ";<br />} <br />function recur(){<br />	global $a;<br />	$a++;<br />	echo "\n\n\n";<br />	debug_print_backtrace();<br />	if($a<10){<br />		iterate();<br />	}<br />} <br /><p>iterate();</p>

你知道这个例子里的程序在干嘛吗?其实我也没看明白,不过这不重要!重要的是他将输出如下内容:

0 recur() called at [C:\htdocs\php_stuff\index.php:8] 

1 iterate() called at [C:\htdocs\php_stuff\index.php:25] 
0 recur() called at [C:\htdocs\php_stuff\index.php:8] 
1 iterate() called at [C:\htdocs\php_stuff\index.php:21] 
2 recur() called at [C:\htdocs\php_stuff\index.php:8] 
3 iterate() called at [C:\htdocs\php_stuff\index.php:25] 
0 recur() called at [C:\htdocs\php_stuff\index.php:8] 
1 iterate() called at [C:\htdocs\php_stuff\index.php:21] 
2 recur() called at [C:\htdocs\php_stuff\index.php:8] 
3 iterate() called at [C:\htdocs\php_stuff\index.php:21] 
4 recur() called at [C:\htdocs\php_stuff\index.php:8] 

5 iterate() called at [C:\htdocs\php_stuff\index.php:25]

7.metaphone()

这个函数返回单词的metaphone值,相同读音的单词具有相同的metaphone值,也就是说这个函数可以帮你判断两个单词的读音是否相同。

不过对中文就无效了。。。

8.natsort()

natsort()能将一个数组以自然排序法进行排列,直接看个例子吧:

<p><?php</p>$items=array('100 apples','5 apples','110 apples','55 apples');<br />sort($items);<br />print_r($items);<br />natsort($items);<br /><p>print_r($items);</p>

输出结果如下:

Array( 

 [0] => 100 apples 
 [1] => 110 apples 
 [2] => 5 apples 
 [3] => 55 apples 
)
Array( 
 [2] => 5 apples 
 [3] => 55 apples 
 [0] => 100 apples 
 [1] => 110 apples 

)

9.levenshtein()

Levenshtein()告诉你两个单词之间的“距离”。它告诉你如果想把一个单词变成另一个单词,需要插入、替换和删除多少字母。 看个例子吧:

<p><?php</p>$dictionary=array("php","javascript","css");<br />$word="japhp";<br />$best_match=$dictionary[0];<br />$match_value=levenshtein($dictionary[0], $word);<br />foreach($dictionary as $w){<br />	$value=levenshtein($word,$w);<br />	if($value<$match_value){ <br />		$best_match=$w;<br />		$match_value=$value;<br />	}<br />}<br /><p>echo "Did you mean the '",$best_match,"' category?";</p>

10.glob()

glob()会让你觉得用opendir(), readdir()和closedir()来寻找文件非常蠢。这个函数返回匹配指定模式的文件名或目录。

该函数返回一个包含有匹配文件 / 目录的数组。如果出错返回 false。

<p><?php</p>foreach(glob("*.php") as $file){<br />	echo "$file\n";<br />}


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 is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

How do you optimize PHP applications for performance?How do you optimize PHP applications for performance?May 08, 2025 am 12:08 AM

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools