search
HomeBackend DevelopmentPHP TutorialSummary of 8 functions commonly used by PHP programmers, PHP programmer summary_PHP tutorial

A summary of 8 functions commonly used by PHP programmers, a summary of PHP programmers

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.

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:

Copy code The code is as follows:

// Function with two default parameters
function foo($arg1 = ”, $arg2 = ”) {
echo “arg1: $arg1n”;
echo “arg2: $arg2n”;
}
foo('hello','world');
/* Output:
arg1: hello
arg2: world
*/
foo();
/* Output:
arg1:
arg2:
*/

The following example is the usage of variable parameters in PHP, which uses the ?func_get_args() method:

Copy code The code is as follows:

// Yes, the parameter list is empty
function foo() {
// Get the array of all incoming parameters
$args = func_get_args();
foreach ($args as $k => $v) {
echo “arg”.($k+1).”: $vn”;
}
}
foo();
/* Nothing will be output */
foo(‘hello’);
/* Output
arg1: hello
*/
foo(‘hello’, ‘world’, ‘again’);
/* Output
arg1: hello
arg2: world
arg3: again
*/

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() and scandir () can be used to find files, please see the following usage:

Copy code The code is as follows:

// Get all files with the suffix PHP
$files = glob(‘*.php’);

print_r($files);
/* Output:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
)
*/

You can also search for a variety of suffixes

Copy code The code is as follows:

// Get PHP files and TXT files
$files = glob(‘*.{php,txt}’, GLOB_BRACE);

print_r($files);
/* Output:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
[4] => log.txt
[5] => test.txt
)
*/

You can also add the path:

Copy code The code is as follows:

$files = glob(‘../images/a*.jpg’);
print_r($files);
/* Output:
Array
(
[0] => ../images/apple.jpg
[1] => ../images/art.jpg
)
*/

If you want to get the absolute path, you can call the ?realpath() function:

Copy code The code is as follows:

$files = glob(‘../images/a*.jpg’);
// applies the function to each array element
$files = array_map(‘realpath’,$files);
print_r($files);
/* output looks like:
Array
(
[0] => C:wampwwwimagesapple.jpg
[1] => C:wampwwwimagesart.jpg
)
*/

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:

Copy code The code is as follows:

echo “Initial: “.memory_get_usage().” bytes n”;
/* Output
Initial: 361400 bytes
*/
//Use memory
for ($i = 0; $i $array []= md5($i);
}
// Delete half of the memory
for ($i = 0; $i unset($array[$i]);
}
echo “Final: “.memory_get_usage().” bytes n”;
/* prints
Final: 885912 bytes
*/
echo “Peak: “.memory_get_peak_usage().” bytes n”;
/* Output peak value
Peak: 13687072 bytes
*/

4. Obtain 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.

Copy code The code is as follows:

print_r(getrusage());
/* Output
Array
(
[ru_oublock] => 0
[ru_inblock] => 0
[ru_msgsnd] => 2
[ru_msgrcv] => 3
[ru_maxrss] => 12692
[ru_ixrss] => 764
[ru_idrss] => 3864
[ru_minflt] => 94
[ru_majflt] => 0
[ru_nsignals] => 1
[ru_nvcsw] => 67
[ru_nivcsw] => 4
[ru_nswap] => 0
[ru_utime.tv_usec] => 0
[ru_utime.tv_sec] => 0
[ru_stime.tv_usec] => 6269
[ru_stime.tv_sec] => 0
)
*/

This structure seems very obscure, unless you know the CPU very well. Some explanations below:

ru_oublock: block output operation
ru_inblock: Block input operation
ru_msgsnd: message sent
ru_msgrcv: message received
ru_maxrss: Maximum resident set size
ru_ixrss: total shared memory size
ru_idrss: Total non-shared memory size
ru_minflt: Page recycling
ru_majflt: Page invalid
ru_nsignals: Received signals
ru_nvcsw: Active context switching
ru_nivcsw: Passive context switching
ru_nswap: Swap area
ru_utime.tv_usec: User mode time (microseconds)
ru_utime.tv_sec: User mode time (seconds)
ru_stime.tv_usec: System kernel time (microseconds)
ru_stime.tv_sec: System kernel time?(seconds)
To see how much CPU your script consumes, we need to look at the "User Mode Time" and "System Kernel Time" values. The seconds and microseconds parts are provided separately. You can divide the microseconds value by 1 million and add it to the seconds value to get the number of seconds with a fractional part.

Copy code The code is as follows:

// sleep for 3 seconds (non-busy)
sleep(3);
$data = getrusage();
echo “User time: “.
($data['ru_utime.tv_sec'] +
$data['ru_utime.tv_usec'] / 1000000);
echo “System time: “.
($data['ru_stime.tv_sec'] +
$data['ru_stime.tv_usec'] / 1000000);
/* Output
User time: 0.011552
System time: 0
*/

Sleep does not occupy system time. We can look at the following example:

Copy code The code is as follows:

// loop 10 million times (busy)
for($i=0;$i }
$data = getrusage();
echo “User time: “.
($data['ru_utime.tv_sec'] +
$data['ru_utime.tv_usec'] / 1000000);
echo “System time: “.
($data['ru_stime.tv_sec'] +
$data['ru_stime.tv_usec'] / 1000000);
/* Output
User time: 1.424592
System time: 0.004204
*/

This took about 14 seconds of CPU time, almost all of which was user time since there were no system calls.

System time is the time the CPU spends executing kernel instructions on system calls. Here is an example:

Copy code The code is as follows:

$start = microtime(true);
// keep calling microtime for about 3 seconds
while(microtime(true) – $start }
$data = getrusage();
echo “User time: “.
($data['ru_utime.tv_sec'] +
$data['ru_utime.tv_usec'] / 1000000);
echo “System time: “.
($data['ru_stime.tv_sec'] +
$data['ru_stime.tv_usec'] / 1000000);
/* prints
User time: 1.088171
System time: 1.675315
*/

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 that is not necessarily the case. 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 .

Copy code The code is as follows:

// this is relative to the loaded script's path
// it may cause problems when running scripts from different directories
require_once(‘config/database.php’);
// this is always relative to this file's path
// no matter where it was included from
require_once(dirname(__FILE__) . ‘/config/database.php’);

The following is using __LINE__ to output some debug information, which will help you debug the program:

Copy code The code is as follows:

// some code
// …
my_debug(“some debug message”, __LINE__);
/* Output
Line 4: some debug message
*/
// some more code
// …
my_debug(“another debug message”, __LINE__);
/* Output
Line 11: another debug message
*/
function my_debug($msg, $line) {
echo “Line $line: $msgn”;
}

6. Generate a unique id

Many friends use md5() to generate unique numbers, but md5() has several shortcomings: 1. Disorder, resulting in reduced 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:

Copy code The code is as follows:

// generate unique string
echo uniqid();
/* Output
4bd67c947233e
*/
// generate another unique string
echo uniqid();
/* Output
4bd67c9472340
*/

This algorithm is generated based on the CPU timestamp, so in a similar time period, 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 precede the ID Add a prefix, such as:

Copy code The code is as follows:

// prefix
echo uniqid(‘foo_’);
/* Output
foo_4bd67d6cd8b8f
*/
// There is more entropy
echo uniqid(”,true);
/* Output
4bd67d6cd8b926.12135106
*/
// All
echo uniqid(‘bar_’,true);
/* Output
bar_4bd67da367b650.43684647
*/

7. Serialization

PHP serialization function may be used 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:

Copy code The code is as follows:

// A complex array
$myvar = array(
‘hello’,
42,
array(1,'two'),
'apple'
);
// Serialization
$string = serialize($myvar);
echo $string;
/* Output
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";}
*/
//Desequential instantiation
$newvar = unserialize($string);
print_r($newvar);
/* Output
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/

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:

Copy code The code is as follows:

// a complex array
$myvar = array(
‘hello’,
42,
array(1,'two'),
'apple'
);
// convert to a string
$string = json_encode($myvar);
echo $string;
/* prints
["hello",42,[1,"two"],"apple"]
*/
// you can reproduce the original variable
$newvar = json_decode($string);
print_r($newvar);
/* prints
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/

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:

Copy code The code is as follows:

$string =
“Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nunc ut elit id mi ultricies
adipiscing. Nulla facilisi. Praesent pulvinar,
sapien vel feugiat vestibulum, nulla dui pretium orci,
non ultricies elit lacus quis ante. Lorem ipsum dolor
sit amet, consectetur adipiscing elit. Aliquam
Pretium ullamcorper urna quis iaculis. Etiam ac massa
sed turpis tempor luctus. Curabitur sed nibh eu elit
mollis congue. Praesent ipsum diam, consectetur vitae
Ornare a, aliquam a nunc. In id magna pellentesque
tellus posuere adipiscing. Sed non mi metus, at lacinia
augue. Sed magna nisi, ornare in mollis in, mollis
sed nunc. Etiam at justo in leo congue mollis.
Nullam in neque eget metus hendrerit scelerisque
eu non enim. Ut malesuada lacus eu nulla bibendum
id euismod urna sodales. “;
$compressed = gzcompress($string);
echo “Original size: “.strlen($string).”n”;
/* Output original size
Original size: 800
*/
echo “Compressed size: “.strlen($compressed).”n”;
/* Output the compressed size
Compressed size: 418
*/
// Decompress
$original = gzuncompress($compressed);

Almost 50% compression ratio. At the same time, you can also use the ?gzencode() and gzdecode() functions to compress, but they use different compression algorithms.

The above are 8 functions that PHP programmers must master. Are they all practical?

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/929671.htmlTechArticleA summary of 8 functions commonly used by PHP programmers. A summary of PHP programmers. Programmers who have done PHP development should know that, There are many built-in functions in PHP. Mastering them can help you in 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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

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

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

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怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

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

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

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

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
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment