


Summary of 9 commonly used functions in PHP development_PHP tutorial
1. Any number of parameters for a function
You may know that PHP allows you to define a function with default parameters. But you may not know that PHP also allows you to define a function with completely arbitrary parameters
Here is an example to show you a function with default parameters:
// 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:
*/
Now let’s take a look at a function with variable parameters , which uses the ?func_get_args() method:
// Yes, the formal parameter list is empty
function foo() {
// Get an 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
Many PHP functions have a relatively long self-explanatory function name, but when you see ?glob(), you may You don't know what this function is used for, unless you are already familiar with it.
You can think of this function as scandir(), which can be used to find files.
// 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
// 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:
$ 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 ?realpath() Function:
$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. Memory usage information
Observing the memory usage of your program allows you to better optimize it your code.
PHP has a garbage collection mechanism and a very complex memory management mechanism. You can find out how much memory your script is using. To know the current memory usage, you can use the memory_get_usage() function. If you want to know the peak memory usage, you can call the memory_get_peak_usage() function.
echo "Initial: ".memory_get_usage()." bytes n";
/* Output
Initial: 361400 bytes
*/
// Use memory
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"; .memory_get_peak_usage()." bytes n";
/* Output peak value
Peak: 13687072 bytes
*/
4. CPU usage information
Using the ?getrusage() function can let you know the CPU usage. Note that this feature is not available under Windows.
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] => > 1
[ru_nvcsw] => 67
[ru_nivcsw] => .tv_sec] => 0
[ru_stime.tv_usec] => 6269
[ru_stime.tv_sec] => 0
)
*/
This structure looks very obscure. , unless you know a lot about CPU. 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 invalidation
ru_nsignals: Signals received
ru_nvcsw: Active context switch
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 values of "User Mode Time" and "System Kernel Time". 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.
// 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 Let’s look at the following example:
// 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: “. : 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:
Copy code
The code is as follows:
$start = microtime(true);
// keep calling microtime for about 3 seconds
($data['ru_stime.tv_sec' ); 🎜>We can see that the above example consumes more CPU.
5. System constants
PHP provides very useful system constants that allow you to get the current line number (__LINE__), file (__FILE__), directory (__DIR__), and 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 the output using __LINE__ Some debug information to help you debug the program:
// 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 people use md5() to generate a unique ID, as shown below:
// generate unique string
echo md5(time() . mt_rand(1, 1000000));
Actually, there is a function called ?uniqid() in PHP that is specifically used to do this:
// generate unique string
echo uniqid();
/* Output
4bd67c947233e
*/
// generate another unique string
echo uniqid();
/* Output
4bd67c9472340
The first few digits of the IDs that come out are the same. This is because the generator depends on the system time. This is actually a very good feature because you can easily sort your IDs. MD5 cannot do this.
You can also add a prefix to avoid duplication of names:
// 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
*/
Username: Password: New user registration bkJia Sanbu Treaty Submission Website Home Page | PHP Industry | WEB Development Materials | Video Tutorials | PHP Open Source | Related Downloads | PHP Job Recruitment | Project Supply and Demand | Resource Sharing | bkJia Chinese Forum Apache | Mysql | PHP | JavaScript | Ajax | XML |
Time: 2011-07-08 00:18 Source: coolshell.cn Author: coolshell.cn Clicks: 5403 times [Font size: Large, Medium, Small] 1. Any number of parameters for a function You may know that PHP allows you to define a default Parameter function. But you may not know that PHP also allows you to define a function with completely arbitrary parameters. Here is an example showing you a function with default parameters: // Function with two default parameters function foo($arg1 = '', $arg2 = '') { echo arg1: $ar
7. Serialization
Will you save a more complex data structure into a database or file? You don’t need to do it yourself Write your own algorithm. PHP has already done it for you, it provides two functions: ?serialize() and unserialize():
// 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
)
*/
This is a native function of PHP, however today JSON is becoming more and more The more popular it is, so after PHP5.2, PHP starts to support JSON. You can use the json_encode() and json_decode() functions
// 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); => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => ; apple
)
*/
This looks more compact and is compatible with Javascript and other languages. But for some very complex data structures, data loss may occur.
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:
pretium ullamcorper urna quis iaculis. gue. Sed magna nisi, ornare in mollis in, mollis
sed nunc. Etiam at justo in leo congue mollis. 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.
9. Register shutdown function
There is a function called ?register_shutdown_function() that allows you to run the code before the entire script is stopped. Let’s look at an example below:
Copy the code
The code is as follows:
// capture the start time
$start_time = microtime(true);
// do some stuff
// ...
// display how long the script took
echo "execution took: ".
(microtime(true) - $start_time).
" seconds.";
The above example is just used to calculate the running time of a certain function. Then, if you call the ?exit() function in the middle of a function, your final code will not be run. Also, if the script is terminated in the browser (the user presses the stop button), it cannot be run.
And when we use register_shutdown_function(), your program will be run even after the script is stopped:
$start_time = microtime(true);
register_shutdown_function('my_shutdown');
// do some stuff
// ...
function my_shutdown() {
global $start_time;
echo "execution took: ".
(microtime(true) - $ start_time).
" seconds.";
}

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

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

In 2025, global digital virtual currency trading platforms are fiercely competitive. This article authoritatively releases the top ten digital virtual currency trading platforms in the world in 2025 based on indicators such as transaction volume, security, and user experience. OKX ranks first with its strong technical strength and global operation strategy, and Binance follows closely with high liquidity and low fees. Platforms such as Gate.io, Coinbase, and Kraken are at the forefront with their respective advantages. The list covers trading platforms such as Huobi, KuCoin, Bitfinex, Crypto.com and Gemini, each with its own characteristics, but investment should be cautious. To choose a platform, you need to consider factors such as security, liquidity, fees, user experience, currency selection and regulatory compliance, and invest rationally

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

In-depth analysis of the top 15 Bitcoin Escape Index: Market Outlook for 2025 This article deeply analyzes fifteen commonly used Bitcoin Escape Index, among which the Bitcoin Rhodl ratio, USDT current wealth management and altcoin seasonal index have reached the Escape Index in 2024, attracting market attention. How should investors deal with potential risks? Let us interpret these indicators one by one and explore reasonable response strategies. 1. Detailed explanation of key indicators AHR999 coin hoarding indicator: Created by ahr999, assisting Bitcoin fixed investment strategy. The current value is 1.21, which is in the wait-and-see range, so it is recommended to be cautious. Link to AHR999 Escape Top Indicator: A supplement to AHR999 Coin Hoarding Indicator, used to identify the top of the market. The current value is 2.48, this week
