search
HomeBackend DevelopmentPHP Tutorial8 essential PHP function development_PHP tutorial
8 essential PHP function development_PHP tutorialJul 13, 2016 am 10:38 AM
phpindivualbuilt-inFunctionCandevelopEssentialmasterofprogrammer

Programmers who have done PHP development should know that there are many built-in functions in PHP. Mastering them can help you become more comfortable in PHP development. This article will share 8 essential PHP functions for development, each of which They are all very practical and I hope all PHP developers can master them.​ ​ 8 essential PHP function development_PHP tutorial

​ 1. Pass any number of function parameters ​ In .NET or JAVA programming, the number of function parameters is generally fixed, but PHP allows you to use any number of parameters.The following example shows you the default parameters of a PHP function: ​ Php code

  1. // Function with two default parameters
  2. function foo($arg1 = ”, $arg2 = ”) {
  3. echo “arg1: $arg1n”;
  4. echo “arg2: $arg2n”;
  5. }
  6. foo(‘hello’,’world’);
  7. /* Output:
  8. arg1: hello
  9. arg2: world
  10. */
  11. foo();
  12. /* Output:
  13. arg1:
  14. arg2:
  15. */
  16. The following example is the usage of variable parameters in PHP, which uses the [url=http://us2.php.net/manual/en/function.func-get-args.php]func_get_args()[/url] method:
  17. // Yes, the parameter list is empty
  18. function foo() {
  19. // Get the array of all incoming parameters
  20. $args = func_get_args();
  21. foreach ($args as $k => $v) {
  22. echo “arg”.($k+1).”: $vn”;
  23. }
  24. }
  25. foo();
  26. /* Nothing will be output */
  27. foo(‘hello’);
  28. /* Output
  29. arg1: hello
  30. */
  31. foo(‘hello’, ‘world’, ‘again’);
  32. /* Output
  33. arg1: hello
  34. arg2: world
  35. arg3: again
  36. */
​ ​ 2. Use glob() to find files ​ The function names of most PHP functions can understand their purpose literally, but when you see glob(), you may not know what it is used for. In fact, glob() is the same as scandir(). It can be used to find files, please see the usage below: ​ Php code
  1. // Get all files with the suffix PHP
  2. $files = glob(‘*.php’);
  3. print_r($files);
  4. /* Output:
  5. Array
  6. (
  7. [0] => phptest.php
  8. [1] => pi.php
  9. [2] => post_output.php
  10. [3] => test.php
  11. )
  12. */
​ You can also search for various suffixes: ​ Php code
  1. // Get PHP files and TXT files
  2. $files = glob(‘*.{php,txt}’, GLOB_BRACE);
  3. print_r($files);
  4. /* Output:
  5. Array
  6. (
  7. [0] => phptest.php
  8. [1] => pi.php
  9. [2] => post_output.php
  10. [3] => test.php
  11. [4] => log.txt
  12. [5] => test.txt
  13. )
  14. */
​ You can also add the path: ​ Php code
  1. $files = glob(‘../images/a*.jpg’);
  2. print_r($files);
  3. /* Output:
  4. Array
  5. (
  6. [0] => ../images/apple.jpg
  7. [1] => ../images/art.jpg
  8. )
  9. */
​ ​ If you want to get the absolute path, you can call the realpath() function: ​ Php code
  1. $files = glob(‘../images/a*.jpg’);
  2. //applies the function to each array element
  3. $files = array_map(‘realpath’,$files);
  4. print_r($files);
  5. /* output looks like:
  6. Array
  7. (
  8. [0] => C:wampwwwimagesapple.jpg
  9. [1] => C:wampwwwimagesart.jpg
  10. )
  11. */
​ ​ 3. Obtain memory usage information ​ PHP's memory recycling mechanism is already very powerful. You can also use PHP scripts to obtain the current memory usage, call the memory_get_usage() function to obtain the current memory usage, and call the memory_get_peak_usage() function to obtain the peak memory usage. The reference code is as follows: ​ Php code
  1. echo “Initial: “.memory_get_usage().” bytes n”;
  2. /* Output
  3. Initial: 361400 bytes
  4. */
  5. //Use memory
  6. for ($i = 0; $i
  7. $array []= md5($i);
  8. }
  9. // Delete half of the memory
  10. for ($i = 0; $i
  11. unset($array[$i]);
  12. }
  13. echo “Final: “.memory_get_usage().” bytes n”;
  14. /* prints
  15. Final: 885912 bytes
  16. */
  17. echo “Peak: “.memory_get_peak_usage().” bytes n”;
  18. /* Output peak value
  19. Peak: 13687072 bytes
  20. */
​ ​ 4. Get CPU usage information ​ After obtaining the memory usage, you can also use PHP's getrusage() to obtain the CPU usage. This method is not available under Windows.    Php代码 
  1. print_r(getrusage());  
  2. /* 输出 
  3. Array 
  4. [ru_oublock] => 0 
  5. [ru_inblock] => 0 
  6. [ru_msgsnd] => 2 
  7. [ru_msgrcv] => 3 
  8. [ru_maxrss] => 12692 
  9. [ru_ixrss] => 764 
  10. [ru_idrss] => 3864 
  11. [ru_minflt] => 94 
  12. [ru_majflt] => 0 
  13. [ru_nsignals] => 1 
  14. [ru_nvcsw] => 67 
  15. [ru_nivcsw] => 4 
  16. [ru_nswap] => 0 
  17. [ru_utime.tv_usec] => 0 
  18. [ru_utime.tv_sec] => 0 
  19. [ru_stime.tv_usec] => 6269 
  20. [ru_stime.tv_sec] => 0 
  21. */  
    这个结构看上出很晦涩,除非你对CPU很了解。下面一些解释: 
  • ru_oublock: 块输出操作
  • ru_inblock: 块输入操作
  • ru_msgsnd: 发送的message
  • ru_msgrcv: 收到的message
  • ru_maxrss: 最大驻留集大小
  • ru_ixrss: 全部共享内存大小
  • ru_idrss:全部非共享内存大小
  • ru_minflt: 页回收
  • ru_majflt: 页失效
  • ru_nsignals: 收到的信号
  • ru_nvcsw: 主动上下文切换
  • ru_nivcsw: 被动上下文切换
  • ru_nswap: 交换区
  • ru_utime.tv_usec: 用户态时间 (microseconds)
  • ru_utime.tv_sec: 用户态时间(seconds)
  • ru_stime.tv_usec: 系统内核时间 (microseconds)
  • ru_stime.tv_sec: 系统内核时间?(seconds)
  要看到你的脚本消耗了多少CPU,我们需要看看“用户态的时间”和“系统内核时间”的值。秒和微秒部分是分别提供的,您可以把微秒值除以100万,并把它添加到秒的值后,可以得到有小数部分的秒数。    Php代码 
  1. // sleep for 3 seconds (non-busy)  
  2. sleep(3);  
  3. $data = getrusage();  
  4. echo “User time: “.  
  5. ($data['ru_utime.tv_sec'] +  
  6. $data['ru_utime.tv_usec'] / 1000000);  
  7. echo “System time: “.  
  8. ($data['ru_stime.tv_sec'] +  
  9. $data['ru_stime.tv_usec'] / 1000000);  
  10. /* 输出 
  11. User time: 0.011552 
  12. System time: 0 
  13. */  
  sleep是不占用系统时间的,我们可以来看下面的一个例子:    Php代码 
  1. // loop 10 million times (busy)  
  2. for($i=0;$i
  3. }  
  4. $data = getrusage();  
  5. echo “User time: “.  
  6. ($data['ru_utime.tv_sec'] +  
  7. $data['ru_utime.tv_usec'] / 1000000);  
  8. echo “System time: “.  
  9. ($data['ru_stime.tv_sec'] +  
  10. $data['ru_stime.tv_usec'] / 1000000);  
  11. /* 输出 
  12. User time: 1.424592 
  13. System time: 0.004204 
  14. */  
      这花了大约14秒的CPU时间,几乎所有的都是用户的时间,因为没有系统调用。  系统时间是CPU花费在系统调用上的上执行内核指令的时间。Here is an example: ​ Php code
  1. $start = microtime(true);
  2. // keep calling microtime for about 3 seconds
  3. while(microtime(true) – $start
  4. }
  5. $data = getrusage();
  6. echo “User time: “.
  7. ($data['ru_utime.tv_sec'] +
  8. $data['ru_utime.tv_usec'] / 1000000);
  9. echo “System time: “.
  10. ($data['ru_stime.tv_sec'] +
  11. $data['ru_stime.tv_usec'] / 1000000);
  12. /* prints
  13. User time: 1.088171
  14. System time: 1.675315
  15. */
​ ​ We can see that the above example consumes more CPU.​ ​ 5. Get system constants ​ PHP provides very useful system constants that allow you to get the current line number (__LINE__), file (__FILE__), directory (__DIR__), function name (__FUNCTION__), class name (__CLASS__), method name (__METHOD__) and namespace ( __NAMESPACE__), much like C language.​ ​ We can think that these things are mainly used for debugging, but not necessarily. For example, we can use ?__FILE__ when including other files (of course, you can also use __DIR__ after PHP 5.3). Here is an example.​ ​ Php code
  1. // this is relative to the loaded script’s path
  2. // it may cause problems when running scripts from different directories
  3. require_once(‘config/database.php’);
  4. // this is always relative to this file’s path
  5. // no matter where it was included from
  6. require_once(dirname(__FILE__) . ‘/config/database.php’);
​ The following is using __LINE__ to output some debug information, which will help you debug the program: ​ Php code
  1. // some code
  2. // … 
  3. my_debug(“some debug message”, __LINE__);
  4. /* Output
  5. Line 4: some debug message
  6. */
  7. // some more code
  8. // … 
  9. my_debug(“another debug message”, __LINE__);
  10. /* Output
  11. Line 11: another debug message
  12. */
  13. function my_debug($msg, $line) {
  14. echo “Line $line: $msgn”;
  15. }
​ ​ 6. Generate unique id ​ Many friends use md5() to generate unique numbers, but md5() has several shortcomings: 1. Disorder, which leads to a decrease in sorting performance in the database. 2. Too long and requires more storage space. In fact, PHP comes with a function to generate a unique id. This function is uniqid().Here’s how to use it: ​ Php code
  1. // generate unique string
  2. echo uniqid();
  3. /* Output
  4. 4bd67c947233e
  5. */
  6. // generate another unique string
  7. echo uniqid();
  8. /* Output
  9. 4bd67c9472340
  10. */
​ ​ This algorithm is generated based on CPU timestamps, so in similar time periods, the first few digits of the ID are the same, which also facilitates the sorting of IDs. If you want to better avoid duplication, you can add a prefix before the ID. ,like: ​ Php code
  1. // Prefix
  2. echo uniqid(‘foo_’);
  3. /* Output
  4. foo_4bd67d6cd8b8f
  5. */
  6. // There is more entropy
  7. echo uniqid(”,true);
  8. /* Output
  9. 4bd67d6cd8b926.12135106
  10. */
  11. // All
  12. echo uniqid(‘bar_’,true);
  13. /* Output
  14. bar_4bd67da367b650.43684647
  15. */
​ ​ 7. Serialization ​ You may use PHP serialization function more and more commonly. When you need to save data to a database or file, you can use the serialize() and unserialize() methods in PHP to achieve serialization and deserialization. , the code is as follows: ​ Php code
  1. // A complex array
  2. $myvar = array(
  3. ‘hello’,
  4. 42,
  5. array(1,’two’),
  6. ‘apple’
  7. );
  8. // Serialization
  9. $string = serialize($myvar);
  10. echo $string;
  11. /* Output
  12. a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3: "two";}i:3;s:5:"apple";}
  13. */
  14. //Desequential instantiation
  15. $newvar = unserialize($string);
  16. print_r($newvar);
  17. /* Output
  18. Array
  19. (
  20. [0] => hello
  21. [1] => 42
  22. [2] => Array
  23. (
  24. [0] => 1
  25. [1] => two
  26. )
  27. [3] => apple
  28. )
  29. */
​ ​ How to serialize into json format? Don’t worry, PHP has already done it for you. Users using PHP 5.2 or above can use the json_encode() and json_decode() functions to serialize json format. The code is as follows: ​ Php code
  1. // a complex array
  2. $myvar = array(
  3. ‘hello’,
  4. 42,
  5. array(1,’two’),
  6. ‘apple’
  7. );
  8. // convert to a string
  9. $string = json_encode($myvar);
  10. echo $string;
  11. /* prints
  12. ["hello",42,[1,"two"],"apple"]
  13. */
  14. // you can reproduce the original variable
  15. $newvar = json_decode($string);
  16. print_r($newvar);
  17. /* prints
  18. Array
  19. (
  20. [0] => hello
  21. [1] => 42
  22. [2] => Array
  23. (
  24. [0] => 1
  25. [1] => two
  26. )
  27. [3] => apple
  28. )
  29. */
​ ​ 8. String compression ​ When we talk about compression, we may think of file compression. In fact, strings can also be compressed.PHP provides gzcompress() and gzuncompress() functions:    Php code 
  1. $string = 
  2. "The truth is that the pain itself is good, it will be successful.
  3. customer service. Now let's get it out of my hands
  4. coaching There is no easy way. It's a pillow,
  5. wisdom or flight of the vestibule, I will not give the price of the hospital,
  6. He did not raise the lake as much as before. Thank you very much.
  7. let it be good, it will be able to attract the customer. Some
  8. the price of any body that is targeted. Yes, and mass
  9. but it was an ugly time of mourning. I'm sorry but I'm sorry
  10. soft homework It is the very day, it will be the result of life
  11. to decorate a, something from now In that great and pushing
  12. to lay the ground But not my fear, but Lacinia
  13. advertise But unless it's big, decorate it in soft, soft
  14. but now. Even at just the right time for homework.  
  15. There is no need to fear chocolate and chocolate
  16. not football. To drink the unsavory lake of football
  17. that euismod urn members “;  
  18. $compressed = gzcompress($string);  
  19. echo "Original size:". strlen($string).”n”;  
  20. /* output original size
  21. Original size: 800
  22. */
  23. echo "Compressed size:". strlen($compressed)."n";  
  24. /* output 剧情后 size
  25. Compressed size: 418
  26. */
  27. // 解剧情  
  28. $original = gzuncompress($compressed);  
    At the same time, you can also use gzencode() and gzdecode() function to compress, only use different compression algorithms.    Above is the 8个安全必备的PHP function, is it not very practical?

原文出处:8个安全必备的PHP function

http://www.bkjia.com/PHPjc/735057.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/735057.htmlTechArticle 做过PHP 可件的电影员光可以这些,PHP has a lot of built-in functions, grasp all of them, it can help You're in the middle of PHP development...
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
如何在技嘉主板上设置键盘启动功能 (技嘉主板启用键盘开机方式)如何在技嘉主板上设置键盘启动功能 (技嘉主板启用键盘开机方式)Dec 31, 2023 pm 05:15 PM

技嘉的主板怎么设置键盘开机首先,要支持键盘开机,一定是PS2键盘!!设置步骤如下:第一步:开机按Del或者F2进入bios,到bios的Advanced(高级)模式普通主板默认进入主板的EZ(简易)模式,需要按F7切换到高级模式,ROG系列主板默认进入bios的高级模式(我们用简体中文来示范)第二步:选择到——【高级】——【高级电源管理(APM)】第三步:找到选项【由PS2键盘唤醒】第四步:这个选项默认是Disabled(关闭)的,下拉之后可以看到三种不同的设置选择,分别是按【空格键】开机、按组

php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

CS玩家的首选:推荐的电脑配置CS玩家的首选:推荐的电脑配置Jan 02, 2024 pm 04:26 PM

1.处理器在选择电脑配置时,处理器是至关重要的组件之一。对于玩CS这样的游戏来说,处理器的性能直接影响游戏的流畅度和反应速度。推荐选择IntelCorei5或i7系列的处理器,因为它们具有强大的多核处理能力和高频率,可以轻松应对CS的高要求。2.显卡显卡是游戏性能的重要因素之一。对于射击游戏如CS而言,显卡的性能直接影响游戏画面的清晰度和流畅度。建议选择NVIDIAGeForceGTX系列或AMDRadeonRX系列的显卡,它们具备出色的图形处理能力和高帧率输出,能够提供更好的游戏体验3.内存电

广联达软件电脑配置推荐;广联达软件对电脑的配置要求广联达软件电脑配置推荐;广联达软件对电脑的配置要求Jan 01, 2024 pm 12:52 PM

广联达软件是一家专注于建筑信息化领域的软件公司,其产品被广泛应用于建筑设计、施工、运营等各个环节。由于广联达软件功能复杂、数据量大,对电脑的配置要求较高。本文将从多个方面详细阐述广联达软件的电脑配置推荐,以帮助读者选择适合的电脑配置处理器广联达软件在进行建筑设计、模拟等操作时,需要进行大量的数据计算和处理,因此对处理器的要求较高。推荐选择多核心、高主频的处理器,如英特尔i7系列或AMDRyzen系列。这些处理器具有较强的计算能力和多线程处理能力,能够更好地满足广联达软件的需求。内存内存是影响计算

主板上的数字音频输出接口-SPDIF OUT主板上的数字音频输出接口-SPDIF OUTJan 14, 2024 pm 04:42 PM

主板上SPDIFOUT连接线序最近我遇到了一个问题,就是关于电线的接线顺序。我上网查了一下,有些资料说1、2、4对应的是out、+5V、接地;而另一些资料则说1、2、4对应的是out、接地、+5V。最好的办法是查看你的主板说明书,如果找不到说明书,你可以使用万用表进行测量。首先找到接地,然后就可以确定其他的接线顺序了。主板vdg怎么接线连接主板的VDG接线时,您需要将VGA连接线的一端插入显示器的VGA接口,另一端插入电脑的显卡VGA接口。请注意,不要将其插入主板的VGA接口。完成连接后,您可以

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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),