8 essential PHP functions and php

Source: Internet
Author: User
Tags glob

8 essential PHP functions and php

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

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:

// 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 usage of PHP indefinite parameters? Func_get_args () method:

// Yes, the parameter list is empty function foo () {// get all input parameter arrays $ args = func_get_args (); foreach ($ args as $ k =>$ v) {echo "arg ". ($ k + 1 ). ": $ v \ n" ;}} foo ();/* No output */foo ('hello');/* output arg1: hello */foo ('hello', 'World', 'again ');/* output arg1: hello arg2: world arg3: again */
2. Use glob () to find files

The function names of most PHP functions can be understood literally, but what do you see? When glob () is used, you may not know what it is used for. In fact, glob () is the same as scandir () and can be used to find files. See the following usage:

// 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 file and TXT file $ 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:

$ Files = glob ('.. /images/*. jpg '); print_r ($ files);/* output: Array ([0] => .. /images/apple.jpg [1] => .. /images/art.jpg )*/

If you want to obtain the absolute path, can you call it? 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:\wamp\www\images\apple.jpg [1] => C:\wamp\www\images\art.jpg ) */
3. Obtain memory usage information

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

Echo "Initial:". memory_get_usage (). "bytes \ n";/* output Initial: 361400 bytes * // memory usage 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";/* prints Final: 885912 bytes */echo "Peak:". memory_get_peak_usage (). "bytes \ n";/* output Peak: 13687072 bytes */
4. Obtain CPU usage information

You can use getrusage () of PHP to obtain the CPU usage. This method is unavailable in 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] => 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 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: 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.

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

// 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:". ($ data ['ru _ stime. TV _sec '] + $ data ['ru _ stime. TV _usec ']/1000000);/* output User time: 1.424592 System 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:

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

We can see that the above example consumes more CPU.

5. Obtain 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.

// 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 uses _ LINE _ to output some debug information, which helps 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: $ msg \ n ";}
6. Generate a unique id

Many friends use md5 () to generate a unique number, but md5 () has several disadvantages: 1. unordered, resulting in 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:

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

// Prefix echo uniqid ('foo _ ');/* output foo_4bd67d6cd8b8f * // more entropy echo uniqid (", true);/* output 4bd67d6cd8b926. 12135106 * // all have echo uniqid ('bar _ ', true);/* output bar_4bd67da1_b2.16.43664647 */
7. serialization

PHP serialization functions are often used. When you need to store data in a database or file, you can use serialize () and unserialize () in PHP () method To achieve serialization and deserialization, the Code is as follows:

// A complex array $ myvar = array ('hello', 42, array (1, 'two'), 'apple '); // serialize $ 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:

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

$ 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: 418 * // decompress $ original = gzuncompress ($ Compressed );

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

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.