PHP common function collection
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
// 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:
// Yes, the formal parameter list is empty
function foo() {
// Get all Array of 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' ; But when you see ?glob(), you may not know what it is used for. In fact, glob(), like scandir(), can be used to find files. Please see the usage below:
Php Code
// 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:
Php code
// 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:
Php code
$files = glob('../images/a*.jpg');
print_r($files) ;
/* Output:
Array
(
[0] => ../images/apple.jpg
[1] => ../images/art.jpg
)
*/
If you To get the absolute path, you can call the ?realpath() function:
Php code
$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. Get memory usage information
PHP’s memory recycling mechanism is already very powerful. You can also use PHP scripts to get the current memory usage and call the memory_get_usage() function to get the current memory usage. In this case, call the memory_get_peak_usage() function to obtain the peak memory usage. The reference code is as follows:
Php code
echo “Initial: “.memory_get_usage().” bytes n”;
/* Output
Initial: 361400 bytes
*/
// Memory usage
for ($i = 0; $ i < 100000; $i++) {
$array []= md5($i);
}
// Delete half of the memory
for ($i = 0; $i < 100000; $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. 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 code inPrint_r (getrusage ()); v] = & GT ; 3
[ru_maxrss] => 12692
[ru_ixrss] => 764
[ru_idrss] => 3864
[ru_minflt] => 94
[ru_majflt] => 0
[ru_nsignals] =& gt; 1 C [ru_nvcsw] = & gt; 67
[ru_nivcsw] = & gt; 4
[ru_nswap] = & gt; 0
[ru_utime.tv_usec] = & gt; 0
[ru_utime.tv_sec] = & gt; 0
[ru_stime.tv_usec] => 6269
[ru_stime.tv_sec] => 0
)
*/
This structure seems very obscure, unless you know the CPU very well. Here are some explanations:
ru_oublock: block output operation
ru_inblock: block input operation
ru_msgsnd: sent message
ru_msgrcv: received message
ru_maxrss: maximum resident set size
ru_ixrss: all shared memory size
ru_idrss: all non Shared memory size
ru_minflt: page recycling
ru_majflt: page invalidation
ru_nsignals: received signals
ru_nvcsw: active context switch
ru_nivcsw: passive context switch
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 " 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.
Php code
// 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:
Php code
// loop 10 million times (busy)
for($i=0;$i<10000000;$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 it 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:
Php code
$start = microtime(true);
// keep calling microtime for about 3 seconds
while(microtime(true) – $start < 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);
/* prints
User time: 1.088171
System time: 1.675315
*/
We can see that the above example is more expensive 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 names (__METHOD__) and namespaces (__NAMESPACE__) are very similar to 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
// 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, this will help you debug the program:
Php code
// 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 a unique number, but md5() has several shortcomings: 1. Unordered, resulting in database Medium sort performance degrades. 2. Too long and requires more storage space. In fact, PHP comes with a function to generate a unique id. This function is uniqid(). The following is the usage:
Php code
// generate unique string
echo uniqid();
/* output
4bd67c947233e
*/
// generate another unique string
echo uniqid();
/* output
4bd67c 9472340
* /
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 Add a prefix, such as:
Php code
// Prefix
echo uniqid('foo_');
/* Output
foo_4bd67d6cd8b8f
*/
// There is more entropy
echo uniqid(",true);
/* Output
4bd67d6cd8b926.12135106
*/
// Both have
echo uniqid('bar_',true);
/* Output
bar_4bd67da367b650.43684647
*/
7. Serialization
PHP serialization You may use this function more often and it is more common. 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
// 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”;}
*/
// Deserialization
$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. Use Users of 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
// 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 the gzcompress() and gzuncompress() functions:
Php code
$string =
“Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nunc ut elit id mi ultricies
adipiscing.
Lorem ipsum dolor
it is important to follow the coaching process. Some of the price of the ullamcorper urn who targeted. Even with the masses, but the ugly time of mourning. Curabitur sed nibh eu elit
soft homework. It is the very home, the consequence of life. In that big kids
tellus to put coaching. But not my fear, but Lacinia
augue. But great unless, to decorate in soft in, soft
but now. Also, just in time for homework.
Nulla in nor needs fear of the Hendrerit scelerisque
eu not. As expected, there is no euismod lake to drink. “;
$compressed = gzcompress($string);
echo "Original size: ". strlen($string)."n";
/* output original size
Original size: 800
*/
echo “Compressed size: “. strlen($compressed).”n”;
/* 解光剧后后图像
Compressed size: 418
*/
// 解光剧
$original = gzuncompress($compressed);
almost has a 50% compression rate. At the same time, you can also use ?gzencode() and gzdecode() function to compress, only use different compression algorithms. , is not very practical? v class="iteye-blog-content-contain" style="font-size: 14px">

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio
