Nine php functions and features that you must know and use very well

Source: Internet
Author: User
Tags glob
The following small series will introduce nine php functions and features that you must know and can use. Very practical! If you need a friend, you can refer to the following nine useful functions in PHP. do you know you have used them?
1. any number of parameters of the 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 all arbitrary parameters.
The following example shows the default parameter functions:
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:
*/

Now let's take a look at a function with an indefinite parameter. it uses the func_get_args () method:
The code is as follows:
// 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. use Glob () to find files
Many PHP functions have a long self-explanatory function name. However, when you see glob (), you may not know what this function is, unless you are familiar with it.

You can think that this function is just like scandir () and can be used to find files.
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
// 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. memory usage information
Observe that the memory usage of your program allows you to better optimize your code.
PHP has a garbage collection mechanism and a complicated memory management mechanism. You can know the memory usage of your script. To know the current memory usage, you can use the memory_get_usage () function. if you want to know the memory usage peak, you can call the memory_get_peak_usage () function.
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. CPU usage information
The getrusage () function allows you to know the CPU usage. Note that this function is not available 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 is 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: the largest and smallest resident set
Ru_ixrss: all shared memory size
Ru_idrss: all non-shared memory sizes
Ru_minflt: page recycling
Ru_majflt: The page is invalid.
Ru_nsignals: Received signal
Ru_nvcsw: active context switching
Ru_nivcsw: passive context switching
Ru_nswap: Swap Zone
Ru_utime. TV _usec: 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 values 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
*/

Sleep does not occupy the system time. let's take a 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 system 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
*/

We can see that the above example consumes more CPU.

5. system constants
PHP provides very useful system constants for you to get the current row number (_ LINE _), FILE (_ FILE _), Directory (_ DIR __), FUNCTION name (_ FUNCTION _), CLASS name (_ CLASS _), METHOD name (_ METHOD _), and NAMESPACE (_ NAMESPACE __), similar to C language.

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 users use md5 () to generate a unique ID, as shown below:
// Generate unique string
Echo md5 (time (). mt_rand (1,000000 ));
In fact, a function called uniqid () in PHP is specifically used to do this:
The code is as follows:
// Generate unique string
Echo uniqid ();
/* Output
4bd67c947233e
*/

// Generate another unique string
Echo uniqid ();
/* Output
4bd67c9472340
*/

You may notice that the first few digits of the generated ID are the same, because the generator depends on the system time, which is actually a very good function, because you can easily sort your IDs. This MD5 cannot be achieved.
You can also add a prefix to avoid duplicate names:
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
*/

In addition, the generated ID is shorter than that generated by MD5, which saves a lot of space.

7. serialization
Will you store a complicated data structure in a database or file? You do not need to write your own algorithms. PHP has already been ready for you. it provides two functions: serialize () and unserialize ():
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
)
*/

This is a native function of PHP. However, JSON is becoming more and more popular today, so after PHP5.2, PHP began to support JSON. you can use json_encode () and json_decode () functions.
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
)
*/

This looks more compact and is compatible with Javascript and other languages. However, some very complex data structures may cause data loss.

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.

9. Register the stop function
There is a function called register_shutdown_function () that allows you to run the code before the entire script is stopped. Let's take a look at the following example:
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 preceding example is only used to calculate the running time of a function. Then, if you call the exit () function in the middle of the function, your final code will not be run. In addition, if the script is terminated in the browser (the user presses the stop button), it cannot be run.
When register_shutdown_function () is used, your program runs even after the script is stopped:
The code is as follows:
$ 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 .";
}

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.