9 Practical PHP functions and functions that must be mastered

Source: Internet
Author: User
Tags glob switches
This article Toceansoft technology, please pay attention to my
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 argumentsAs 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 is an example of an optional parameter://function with 2 optional arguments
function foo ($arg 1 = ", $arg 2 =") {echo "arg1: $arg 1n";
echo "ARG2: $arg 2n";} Foo (' Hello ', ' world ');
/* Prints:
Arg1:hello
Arg2: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 empty
function foo () {//Returns an array of all passed arguments
$args = Func_get_args (); foreach ($args as $k = = $v) {
echo "Arg". ($k + 1). ": $vn";
}}foo ();
/* Prints Nothing */foo (' hello ');
/* Prints
Arg1:hello
*/foo (' Hello ', ' world ', ' again ');
/* Prints
Arg1:hello
Arg2:world
Arg3:again
*/2, using Glob () to find FilesMany 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 informationBy 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";
/* Prints
initial:361400 bytes
*///Let's use up some memory
for ($i = 0; $i < 100000; $i + +) {
$array []= MD5 ($i);
}//let ' s remove half of the array
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";
/* Prints
peak:13687072 bytes
*/4, CPU usage informationTo do this, we use the Getrusage () function. Keep in mind that this function is not available for Windows platforms. Print_r (Getrusage ());
/* Prints
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] = 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] = 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 operations
Ru_inblock:block input Operations
Ru_msgsnd:messages sent
Ru_msgrcv:messages received
Ru_maxrss:maximum resident Set Size
Ru_ixrss:integral Shared Memory Size
Ru_idrss:integral unshared Data size
Ru_minflt:page reclaims
Ru_majflt:page faults
Ru_nsignals:signals received
Ru_nvcsw:voluntary Context Switches
Ru_nivcsw:involuntary Context Switches
Ru_nswap:swaps
Ru_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 a script consumes, we need to look at the values of the ' 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 take a 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);/* Prints
User time:0.011552
System time:0
* * CPU usage is very low even though the script is running for about 3 seconds. 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);/* Prints
User time:1.424592
System time:0.004204
*/This took about 1.4 seconds of CPU time, but almost all of them were 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 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
* * 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 ConstantsPHP 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 containing other script files, use the __FILE__ constant (or use the PHP5.3 new __DIR__ constant)://This is relative to the loaded script ' s path
It may cause problems if running scripts from different directories
Require_once (' config/database.php ');//This is the relative to this file ' s path
No matter where it is included from
Require_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__);
/* Prints
Line 4:some Debug Message
*///some more code
...
My_debug ("Another debug Message", __line__);
/* Prints
Line 11:another Debug Message
*/function My_debug ($msg, $line) {
echo "line $line: $MSGN";
}6, generate a unique identifierIn 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 string
echo MD5 (Time (). Mt_rand (1,1000000)); There is actually a PHP function named Uniqid (), ismeant to being used for this.//generate unique string
Echo Uniqid ();
/* Prints
4bd67c947233e
*///generate another unique string
Echo Uniqid ();
/* Prints
4bd67c9472340
*/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 Prefix
echo uniqid (' Foo_ ');
/* Prints
foo_4bd67d6cd8b8f
*///with more entropy
Echo Uniqid (", true);
/* Prints
4bd67d6cd8b926.12135106
*///both
echo uniqid (' Bar_ ', true);
/* Prints
bar_4bd67da367b650.43684647
*/This function will produce a shorter string than MD5 (), which can save some space.7, serializationHave 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 using the Serialize () and Unserialize () functions://a complex array
$myvar = Array (
' Hello ',
42,
Array (1, ' both '),
' Apple '
);//Convert to a string
$string = serialize ($myvar); Echo $string;
/* Prints
A: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);
/* Prints
Array
(
[0] = = Hello
[1] = 42
[2] = = Array
(
[0] = 1
[1] =
) [3] = + Apple
)
*/This is a 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 ',
42,
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);
/* Prints
Array
(
[0] = = Hello
[1] = 42
[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, compressed stringWhen it comes to compression, we usually think of file compression, such as ZIP compression. String compression is also possible in PHP, but does not involve any compressed files. In the following example, we will take advantage of the gzcompress () and Gzuncompress () functions: $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 pretium orci,
Non ultricies elit lacus quis ante. Lorem ipsum dolor
Sit amet, consectetur adipiscing elit. Aliquam
Pretium ullamcorper 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 ";
/* Prints
Original size:800
*/echo "Compressed Size:". Strlen ($compressed). " n ";
/* Prints
Compressed 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 functionThere 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 the run://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."; 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.";
} like my article, please pay attention to my toceansoft
  • 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.