8 required PHP function instance code _ php instance

Source: Internet
Author: User
Tags glob
This article will share eight essential PHP functions, all of which are very useful: passing any number of function parameters and using glob () search for files, obtain memory usage information, obtain CPU usage information, obtain system constants, generate unique IDs, serialize, and compress strings. Very practical 8 PHP functions. Programmers who have developed PHP should be clear that PHP has many built-in functions and can master them to help you better develop PHP, this article will share eight essential PHP functions, all of which are very practical and I hope all PHP developers can master them.
1. pass any number of function parameters
2. Use glob () to find files
3. Obtain memory usage information
4. Obtain CPU usage information
5. Obtain system Constants
6. Generate a unique id
7. serialization
8. String Compression

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

The Code is as follows:


// Functions with two default parameters
Function foo ($ arg1 = ", $ arg2 = "){
Echo "arg1: $ arg1 \ n ";
Echo "arg2: $ arg2 \ n ";
}
Foo ('hello', 'World ');
/* Output:
Arg1: hello
Arg2: world
*/
Foo ();
/* Output:
Arg1:
Arg2:
*/
The following example shows the variable parameter usage of PHP. It uses the func_get_args () method:
// Yes, the parameter list is empty
Function foo (){
// Obtain the array of all input parameters
$ Args = func_get_args ();
Foreach ($ args as $ k =>v v ){
Echo "arg". ($ k + 1). ": $ v \ n ";
}
}
Foo ();
/* Nothing will be output */
Foo ('hello ');
/* Output
Arg1: hello
*/
Foo ('hello', 'World', 'again ');
/* Output
Arg1: hello
Arg2: world
Arg3: again
*/

2. You can use glob () to find the function names of most PHP functions in a file. However, when you see glob, you may not know what this is for. In fact, glob () is the same as scandir () and can be used to find files. Please refer to the following usage:

The Code is as follows:


// Obtain all files suffixed with 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 find multiple extension names:

The Code is as follows:


// Retrieve the PHP 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 following path:

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 obtain the absolute path, you can call the realpath () function:

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: \ wamp \ www \ images \ apple.jpg
[1] => C: \ wamp \ www \ images \ art.jpg
)
*/

3. Obtain memory usage information the PHP memory recovery mechanism is very powerful. You can also use the PHP script to obtain the current memory usage and call the memory_get_usage () function to obtain the current memory usage, call the memory_get_peak_usage () function to obtain the peak memory usage. The reference code is as follows:

The Code is as follows:


Echo "Initial:". memory_get_usage (). "bytes \ n ";
/* Output
Initialize: 361400 bytes
*/
// Memory usage
For ($ I = 0; I I <100000; $ I ++ ){
$ Array [] = md5 ($ I );
}
// Delete half of the memory
For ($ I = 0; I 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. Obtain the CPU usage information to obtain the memory usage, or use getrusage () of PHP to obtain the CPU usage. This method is unavailable in windows.

The Code is as follows:


Print_r (getrusage ());
/* Output
Array
(
[Ru_oublock] => 0
[Ru_inblock] => 0
[Ru_msgsnd] => 2
[Ru_msgrcv] => 3
[Ru_maxrss] = & gt; 12692
[Ru_ixrss] = & gt; 764
[Ru_idrss] = & gt; 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] = & gt; 6269
[Ru_stime. TV _sec] => 0
)
*/


This structure seems obscure unless you know the CPU. The following 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 failure ru_nsignals: Received Signal ru_nvcsw: Active context switching ru_nivcsw: passive context switching ru_nswap: swap zone Duration: User State time (microseconds) ru_utime. TV _sec: User State 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 value of "user-mode time" and "System Kernel Time. Second and microsecond are provided separately. You can divide the microsecond value by 1 million and add it to the second value to obtain the number of seconds with a decimal part.

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
*/


It does not take up the system time. Let's look at the following example:

The Code is as follows:


// Loop 10 million times (busy)
For ($ I = 0; I 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
Time: 0.004204
*/


This took about 14 seconds of CPU time, almost all of which were user time, because there was no system call. The traditional time is the time when the CPU spends executing kernel commands on system calls. The following is an example:

The Code is as follows:


$ 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
Time: 1.675315
*/


The above example consumes more CPU.

5. Retrieving System constants PHP provides very useful system constants that allow you to obtain the current row number (_ LINE _), FILE (_ FILE __), directory (_ DIR _), FUNCTION name (_ FUNCTION _), CLASS Name (_ CLASS _), METHOD Name (_ METHOD __) it is similar to the NAMESPACE (_ NAMESPACE.
We can think that these things are mainly used for debugging, but they are not necessarily the same. For example, we can use them when include other files? _ FILE _ (of course, you can also use _ DIR _ after PHP 5.3). The following is an example.

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 encoded ded from
Require_once (dirname (_ FILE _). '/config/database. php ');


The following uses _ LINE _ to output some debug information, which helps you debug the program:

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: $ msg \ n ";
}

6. Generate a unique id many friends use md5 () to generate a unique id. However, md5 () has several disadvantages: 1. unordered, leading to a decline in database sorting performance. 2. It is too long and requires more storage space. In fact, PHP comes with a function to generate a unique id. This function is uniqid (). The usage is as follows:

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 time stamp. Therefore, the first few digits of the id are the same in a similar period of time, which facilitates id sorting. If you want to avoid duplication, you can add a prefix before the id, for example:

The Code is as follows:


// Prefix
Echo uniqid ('foo _');
/* Output
Foo_4bd67d6cd8b8f
*/
// More entropy
Echo uniqid (", true );
/* Output
4bd67d6cd8b926. 12135106
*/
// All have
Echo uniqid ('bar _ ', true );
/* Output
Bar_4bd67da% B %.4%4647
*/

7. serialization PHP serialization functions may be widely used and common. When you need to store data in a database or file, you can use serialize () in PHP () and the unserialize () method to implement serialization and deserialization. The Code is as follows:

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 ";}
*/
// Reverse sample
$ Newvar = unserialize ($ string );
Print_r ($ newvar );
/* Output
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/


How to serialize data to json format? Rest assured that php is ready for you. Users who use php 5.2 or later can use the json_encode () and json_decode () functions to serialize data in json format, the Code is as follows:

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:

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 presponorci,
Non ultricies elit lacus quis ante. Lorem ipsum dolor
Sit amet, consectetur adipiscing elit. Aliquam
Prepolicullamcorper 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 ";
/* Original output size
Original size: 800
*/
Echo "Compressed size:". strlen ($ compressed). "\ n ";
/* Output compressed size
Compressed size: 418
*/
// Extract
$ Original = gzuncompress ($ compressed );


The compression ratio is almost 50%. At the same time, you can use the gzencode () and gzdecode () functions to compress, instead of using different compression algorithms.

The above eight PHP functions are essential for development. Are they all very practical?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.