Nine useful PHP functions and functions that must be known [goto]

Source: Internet
Author: User
Tags glob
9 useful PHP functions and functions that must be known [goto]

Even if you use PHP for many years, you will occasionally discover functions and functions that you have never known. Some of them are very useful, but they are not being fully utilized. Not everyone is going to read the manuals and function references from one page to the next!

1, the function of any number of parameters

As you probably already know, PHP allows you to define the functions of optional parameters. But there are also methods that allow any number of function parameters to be fully allowed. The following are examples of optional parameters:

function with 2 optional argumentsfunction foo ($arg 1 = ", $arg 2 =") {echo "arg1: $arg 1n"; echo "arg2: $arg 2n";} Foo (' Hello ', ' world ');/* Prints:arg1:helloarg2:world*/foo ();/* prints:arg1:arg2:*/

Now let's look at how to create a function that accepts any number of arguments. This time you need to use the Func_get_args () function:

Yes, the argument list can be emptyfunction foo () {//Returns a array of all passed arguments $args = Func_get_args () ; foreach ($args as $k = + $v) {  echo "arg". $k + 1). ": $vn"; }}foo ();/* Prints Nothing */foo (' hello ');/* Printsarg1:hello*/foo (' hello ', ' world ', ' again ');/* PRINTSARG1:HELLOARG2: worldarg3:again*/

2. Use Glob () to find files

Many PHP functions have long descriptive names. However, it may be difficult to say what the glob () function can do unless you have used it many times and become familiar with it. You can think of it as a more powerful version than the Scandir () function, and you can search for files in a certain pattern.

Get all PHP files$files = glob (' *.php ');p rint_r ($files);/* output looks like:array (    [0] = = phptest.php    [1] = > pi.php    [2] = post_output.php    [3] = test.php) */

You can get multiple files like this:

Get all PHP files and txt files$files = glob (' *.{ Php,txt} ', Glob_brace);p Rint_r ($files);/* output looks like:array (    [0] = phptest.php    [1] = pi.php    [2] = post_output.php    [3] = test.php    [4] = = Log.txt    [5] = = test.txt) */

Note that these files can actually return a path, depending on the query criteria:

$files = Glob ('.. /images/a*.jpg ');p rint_r ($files);/* output looks like:array (    [0] = =. /images/apple.jpg    [1] = =. /images/art.jpg) */

If you want to get the full path of each file, you can call the Realpath () function:

$files = Glob ('.. /images/a*.jpg '),//Applies the function to each array element$files = Array_map (' Realpath ', $files);p Rint_r ($files);/* Output looks like:array (    [0] = C:wampwwwimagesapple.jpg    [1] = c:wampwwwimagesart.jpg) */

3. Memory usage Information

By detecting the memory usage of the script, it facilitates the optimization of the code. PHP provides a garbage collector and a very complicated memory manager. The amount of memory used when the script executes, with a rise and fall. To get the current memory usage, we can use the Memory_get_usage () function. If you need to get the highest memory usage at any point in time, you can use the Memory_limit () function.

echo "Initial:". Memory_get_usage (). "Bytes n";/* printsinitial:361400 bytes*///Let's use up some memoryfor ($i = 0; $i < 100000; $i + +) {$array []= MD5 ($i);} Let's remove half of the arrayfor ($i = 0; $i < 100000; $i + +) {unset ($array [$i]);} echo "Final:". Memory_get_usage (). "Bytes n";/* printsfinal:885912 Bytes*/echo "Peak:". Memory_get_peak_usage (). "bytes n ";/* printspeak:13687072 bytes*/

4. CPU usage Information

To do this, we use the Getrusage () function. Keep in mind that this function is not available for Windows platforms.

Print_r (Getrusage ());/* Printsarray (    [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] = [    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 may seem a bit cryptic unless you already have system administrator privileges. The following is a specific description of each value (you do not need to remember these):

Ru_oublock:block output Operationsru_inblock:block input operationsru_msgsnd:messages sentru_msgrcv:messages Receivedru_maxrss:maximum resident set Sizeru_ixrss:integral shared memory sizeru_idrss:integral unshared data sizeru_m Inflt:page reclaimsru_majflt:page faultsru_nsignals:signals receivedru_nvcsw:voluntary context SWITCHESRU_NIVCSW: Involuntary context Switchesru_nswap:swapsru_utime.tv_usec:user time used (microseconds) Ru_utime.tv_sec:user time Used (seconds) Ru_stime.tv_usec:system time used (microseconds) Ru_stime.tv_sec:system time used (seconds)

To know how much CPU power the script consumes, we need to look at the values of ' User Time ' and ' system time ' two parameters. The seconds and microseconds sections are provided separately by default. You can divide by 1 million microseconds and add seconds to the parameter value to get the total number of seconds in a decimal. Let's look at an example:

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);/* Printsuser Time:0.011552system time:0*/

Although the script ran for about 3 seconds, the CPU utilization was very low. Because the script does not actually consume CPU resources during the sleep run. There are many other tasks that may take a while, but do not occupy CPU time like waiting for disk operations. So as you can see, the actual length of CPU usage and uptime is not always the same. Here is an example:

Loop 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);/* Printsuser Time:1.424592system time:0.004204*/

This took about 1.4 seconds of CPU time, but almost all of it was user time because there was no system call. System time is the amount of CPU overhead that is spent executing system calls to the program. Here is an example:

$start = Microtime (TRUE);//Keep calling Microtime for about 3 Secondswhile (Microtime (True)-$start < 3) {} $data = Get Rusage (); 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);/* Printsuser Time:1.088171system time:1.675315*/

Now we have quite a lot of system time to occupy. This is because the script calls the Microtime () function multiple times, and the function needs to make a request to the operating system to get the time required. You may also notice that the running time is added up to less than 3 seconds. This is because there is a possibility that other processes exist on the server at the same time, and the script does not have 100% full 3 second duration of CPU usage.

5. Magic constant

PHP provides access to the current line number (__line__), file path (__file__), directory path (__dir__), function name (__function__), class name (__class__), method name (__method__), and namespace (__ NAMESPACE__) and other useful magic constants. Not one in this article, but I'll tell you about some use cases. When you include other script files, use the __FILE__ constant (or use the PHP5.3 new __DIR__ constant):

This was relative to the loaded script ' s path//it could cause problems when running scripts from different directoriesreq Uire_once (' config/database.php ');//This is the relative to this file ' s path//no matter where it was included fromrequ Ire_once (DirName (__file__). '/config/database.php ');

Using __line__ makes debugging easier. You can track the specific line number.

Some code//my_debug ("Some debug message", __line__);/* Printsline 4:some debug message*///Some more code//... my_ Debug ("Another debug Message", __line__);/* printsline 11:another Debug message*/function my_debug ($msg, $line) {echo "L INE $line: $MSGN ";}

6. Generate Unique Identifiers

In some scenarios, you may need to generate a unique string. I see a lot of people using the MD5 () function, even if it doesn't exactly mean this purpose:

Generate unique Stringecho MD5 (time (). Mt_rand (1,1000000));

There is actually a PHP function named Uniqid () which is meant to being used for this.

Generate unique Stringecho uniqid ();/* prints4bd67c947233e*///generate another unique Stringecho uniqid ();/* PRINTS4B d67c9472340*/

You may notice that, although the string is unique, the first few characters are similar because the resulting string is related to the server time. But in fact there is also a friendly aspect, since each newly generated ID is sorted alphabetically, so the ordering becomes simple. To reduce the probability of repetition, you can pass a prefix, or a second parameter to increase the entropy:

With Prefixecho uniqid (' foo_ ');/* printsfoo_4bd67d6cd8b8f*///with more Entropyecho uniqid (', true);/* prints4bd67d6cd8b926.12135106*///bothecho uniqid (' Bar_ ', true);/* printsbar_4bd67da367b650.43684647*/

This function will produce a shorter string than MD5 (), which can save some space.

7. Serialization

Have you ever encountered a situation where you need to store a complex variable in a database or text file? You may not be able to think of a good way to format a string and convert an array or object, and PHP has prepared this feature for you. There are two popular ways to serialize variables. Here is an example of using the Serialize () and Unserialize () functions:

A complex Array$myvar = array (' Hello ',, Array (1, ' both '), ' Apple ');/convert to a string$string = serialize ($myvar); echo $string;/* printsa:4:{i:0;s:5: "Hello"; I:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3: "Both";} I:3;s:5: "Apple";} *///You can reproduce the original Variable$newvar = Unserialize ($string);p rint_r ($newvar);/* Printsarray (    [0] = > Hello    [1] = [    2] = = Array        (            [0] = 1            [1] +-        )    [3] = apple) */

This is the native PHP serialization method. However, thanks to JSON's popularity in recent years, PHP5.2 has added support for JSON format. Now you can use the Json_encode () and Json_decode () functions:

A complex Array$myvar = array (' Hello ',, Array (1, ' both '), ' Apple ');/convert to a string$string = Json_encode ($myvar echo $string;/* prints["Hello", 42,[1, "I", "Apple"]*///you can reproduce the original Variable$newvar = Json_decode ( $string);p Rint_r ($newvar);/* Printsarray (    [0] = = Hello    [1] =    [2] = = Array        (            [0] = = 1            [1] = (        )    [3] = apple) */

This will be more effective, especially compatible with many other languages such as JavaScript. However, for complex objects, some information may be lost.

8. Compressing strings

$string = "Lorem ipsum dolor sit amet, consecteturadipiscing elit. Nunc ut elit id mi ultriciesadipiscing. Nulla Facilisi. Praesent pulvinar,sapien vel feugiat vestibulum, nulla dui pretium orci,non ultricies elit lacus quis ante. Lorem ipsum dolorsit amet, consectetur adipiscing elit. Aliquampretium ullamcorper Urna quis iaculis. Etiam ac massased turpis tempor luctus. Curabitur sed nibh eu elitmollis congue. Praesent ipsum diam, Consectetur vitaeornare A, aliquam a nunc. In ID magna pellentesquetellus posuere adipiscing. Sed non mi metus, at Laciniaaugue. Sed magna Nisi, Ornare in mollis in, mollissed nunc. Etiam at Justo in Leo Congue mollis. Nullam in Neque eget metus hendrerit scelerisqueeu non enim. Ut malesuada lacus eu nulla bibendumid euismod urna sodales. "; $compressed = Gzcompress ($string); echo" Original size: ". Strlen ($string). " n ";/* printsoriginal Size:800*/echo" Compressed size: ". Strlen ($compressed). " n ";/* printscompressed size:418*///getting it back$original = GzuncoMpress ($compressed); 

The compression rate of this operation can reach about 50%. Additional functions Gzencode () and Gzdecode () can achieve similar results by using different compression algorithms.

9. Registration Stop function

There is a function called register_shutdown_function (), which allows you to execute some specified code before a script finishes running. Suppose you need to capture some baseline statistics before the end of the script execution, such as the length of time to run:

Capture the start Time$start_time = Microtime (TRUE);//Do some stuff//...//display how long the script Tookecho "exec Ution took: ".  (Microtime (True)-$start _time).  " seconds. ";

This seems trivial, you just need to add the relevant code at the end of the script run. But if you call the exit () function, the code will not run. Additionally, if there is a fatal error, or if the script is accidentally terminated by the user, it may not be able to run again. When you use the Register_shutdown_function () function, the code continues to execute, regardless of whether the script stops running:

$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. ";}

English Manuscript: 9 useful PHP Functions and Features you need to Know | Nettuts
Translation finishing: 9 useful PHP functions and functions you must know | Mango

  • Related Article

    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.