Nine PHP functions and functions you need to know

Source: Internet
Author: User
Tags glob
9 PHP functions and functions you need to know
Even if we use PHP for many years, some features and features may not be found or underutilized, and we will find them useful once we find them. However, not all of us have read PHP manuals and functional references from the beginning to the beginning!

1. Function and any number of arguments
As you may already know, PHP allows us to define the functions of optional parameters. But there are also any number of function parameter methods that are fully allowed.

First, the following example is an optional parameter:

View sourceprint?01//function with 2 optional arguments

function foo ($arg 1 = ", $arg 2 =") {

echo "Arg1: $arg 1\n";

echo "ARG2: $arg 2\n";

05}

Foo (' Hello ', ' world ');

/* Prints:

Arg1:hello

Arg2:world

10 */

one foo ();

/* Prints:

Arg1:

ARG2:

15 */

Now, let's see how you can create a function to accept any number of arguments. This time, we're going to use the Func_get_args () function:

View sourceprint?01//Yes, the argument list can be empty

function foo () {

//Returns an array of all passed arguments

$args = Func_get_args ();

($args as $k = $v) {

echo "Arg". ($k + 1). ": $v \ n";

07}

08}

* Foo ();

Ten/* Prints nothing */

One foo (' Hello ');

*//Prints

Arg1:hello

14 */

A. Foo (' Hello ', ' world ', ' again ');

*//Prints

Arg1:hello

Arg2:world

Arg3:again

20 */

2. Use the Glob () function to find a file
Many PHP built-in functions have a very long name. However, it may be difficult to explain what the function is, if you do not use Glob (), unless you are already very familiar with this function.

It is more like a scandir () function-enhanced version. It allows you to search for files by using patterns.

View sourceprint?01//Get all PHP files

$files = Glob (' *.php ');

Print_r ($files);

/*/output looks like:

Array

06 (

[0] = = phptest.php

[1] = pi.php

[2] = post_output.php

Ten [3] = test.php

11)

12 */

This allows you to obtain multiple file types:

View sourceprint?01//Get all PHP files and txt files

$files = Glob (' *.{ Php,txt} ', glob_brace);

Print_r ($files);

/*/output looks like:

Array

06 (

[0] = = phptest.php

[1] = pi.php

[2] = post_output.php

Ten [3] = test.php

One [4] = Log.txt

[5] = Test.txt

13)

14 */

Note that these files are actually able to return a path based on your query.

View Sourceprint?1 $files = Glob ('.. /images/a*.jpg ');

2 Print_r ($files);

3/* Output looks like:

4 Array

5 (

6 [0] = =. /images/apple.jpg

7 [1] = =. /images/art.jpg

8)

9 */

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

View sourceprint?01 $files = Glob ('.. /images/a*.jpg ');

Applies//The function to each array element

$files = Array_map (' Realpath ', $files);

Print_r ($files);

/*/output looks like:

Array

07 (

[0] = C:\wamp\www\images\apple.jpg

[1] = C:\wamp\www\images\art.jpg

10)

11 */

3. Memory usage Information
By observing your script's memory usage, you can optimize your code accordingly.

PHP has a garbage collector and a fairly complex memory manager. When your script starts, it begins to use the memory formally. Depending on the execution of the script, memory usage will rise and will also decrease. To get the current memory usage, we can use the Memory_get_usage () function. And can get the highest point of memory usage at any time, here is an example of using the Memory_get_usage () function.

View sourceprint?01 echo "Initial:". Memory_get_usage (). "Bytes \ n";

Prints/*

initial:361400 bytes

04 */

/Let's use up some memory

for ($i = 0; $i < 100000; $i + +) {

$array []= MD5 ($i);

08}

/Let's remove half of the array

Ten for ($i = 0; $i < 100000; $i + +) {

Unset ($array [$i]);

12}

echo "Final:". Memory_get_usage (). "Bytes \ n";

*//Prints

final:885912 bytes

16 */

echo "Peak:". Memory_get_peak_usage (). "Bytes \ n";

*//Prints

peak:13687072 bytes

20 */

4. CPU usage Information
To do this, we will use the Getrusage () function. Keep in mind that this function cannot be applied to the Windows platform.

View sourceprint?01 Print_r (Getrusage ());

Prints/*

Array

04 (

[Ru_oublock] = 0

[Ru_inblock] = 0

[RU_MSGSND] = 2

[RU_MSGRCV] = 3

[Ru_maxrss] = 12692

[Ru_ixrss] = 764

One [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

22)

23 */

This may seem mysterious and difficult to understand, unless you have experience with the system administrator, the following is an introduction to each value (perhaps you do not need to remember these):

Ru_oublock: Block output operation
Ru_inblock: Block input operation
ru_msgsnd: Mail Sending
RU_MSGRCV: Messages Received
Ru_maxrss: Maximum resident set size
Ru_ixrss: The size of the integral shared memory
Ru_idrss: Points non-share data
Ru_minflt: Page Recycling
Ru_majflt: Page Error
Ru_nsignals: Signal Reception
RU_NVCSW: Automatic Context Switch
RU_NIVCSW: Non-automatic context switch
Ru_nswap: Expired
Ru_utime.tv_usec: User usage time (microseconds)
Ru_utime.tv_sec: User usage time (seconds)
RU_STIME.TV_USEC: System usage time (microseconds)
RU_STIME.TV_SEC: System usage time (seconds)
To see how much CPU power is consumed by the script, we need to observe the values of user time and system time. The seconds and milliseconds are provided independently by default. You can put a value of 1 million milliseconds and convert it to a value of seconds, as the total number of seconds for a decimal number.

Let's look at an example:

View sourceprint?01//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);

Ten/* Prints

One User time:0.011552

System time:0

13 */

Although the script took about 3 seconds to run, the CPU utilization was very, very low. Because sleep works, the script does not actually consume CPU resources. Of course, there are other tasks that may actually require a wait time, but you should never wait for CPU time with read-write operations on the disk. So you can see that CPU usage is not always the same as the actual length of the runtime.

Here is another example.

View sourceprint?01//loop million times (busy)

for ($i =0; $i < 10000000; $i + +) {

03}

$data = Getrusage ();

echo "User time:".

($data [' ru_utime.tv_sec '] +

$data [' ru_utime.tv_usec ']/1000000);

echo "System time:".

($data [' ru_stime.tv_sec '] +

Ten $data [' ru_stime.tv_usec ']/1000000);

One/* Prints

User time:1.424592

System time:0.004204

14 */

This took about 1.4 seconds of CPU time. Almost all of this is time spent by the user, and the system has not been called.

The system time is the kernel system call time that is represented by the program that is executing on the CPU that divides the time. (who has a more concise description?) help!) Here is an example:

View sourceprint?01 $start = Microtime (true);

//Keep calling Microtime for about 3 seconds

while (Microtime (true)-$start < 3) {

04}

$data = Getrusage ();

echo "User time:".

($data [' ru_utime.tv_sec '] +

$data [' ru_utime.tv_usec ']/1000000);

echo "System time:".

Ten ($data [' ru_stime.tv_sec '] +

One $data [' ru_stime.tv_usec ']/1000000);

*//Prints

User time:1.088171

System time:1.675315

15 */

5. Magic Constants
PHP provides a way to get the current line number (__line__), get the File path method (__file__), directory (__dir__), function name (__functtion__), class name (__class__), method name (__method__), and namespace (__namespace__). These are the usual magic constants. I'm afraid the only thing we use most is (__file__).

Rikku is not going to explain it all, but it will say a few use cases.

It's a good idea to include other scripts, of course. ((__dir__) requires PHP 5.3 or higher):

View Sourceprint?1//This was relative to the loaded script ' s path

2//It may cause problems if running scripts from different directories

3 require_once (' config/database.php ');

4//This is all relative to this file ' s path

5//No matter where it was included from

6 require_once (DirName (__file__). '/config/database.php ');

Using __line__ to make debugging easier, you can track line numbers:

View sourceprint?01//Some code

02//...

My_debug ("Some debug message", __line__);

*/* Prints

Line 4:some Debug Message

06 */

//Some more code

08//...

My_debug ("Another debug Message", __line__);

Ten/* Prints

Line 11:another Debug Message

12 */

function My_debug ($msg, $line) {

echo "line $line: $msg \ n";

15}

6. Generate a unique ID
In some cases, you need to generate a unique string. I see a lot of people using this MD5 () function, even if he's not entirely used for this purpose:

View sourceprint?1//Generate unique string

2 echo MD5 (Time (). Mt_rand (1,1000000));

There's actually a special PHP function called Uniqid () that exists for this purpose:

View sourceprint?01//Generate unique string

Echo Uniqid ();

Prints/*

4BD67C947233E, Geneva

05 */

Generate//Another unique string

Uniqid Echo ();

/* Prints

4bd67c9472340

10 */

You may notice that even the only strings they have are similar to the first few characters. This is because the resulting string is associated to the server time. There is actually a very good side effect, because each newly generated ID will be sorted alphabetically after the build, thus eliminating the logical action of our sort.

To reduce the chance of repetition, you can pass a prefix, or increment in the second parameter.

View sourceprint?01//with prefix

Uniqid Echo (' Foo_ ');

Prints/*

FOO_4BD67D6CD8B8F, Geneva

05 */

//With more entropy

Uniqid Echo (", true);

/* Prints

4bd67d6cd8b926.12135106

10 */

One//both

echo uniqid (' Bar_ ', true);

/* Prints

bar_4bd67da367b650.43684647

15 */

This feature will generate a shorter string than the MD5 () generation, which will also save you space.

7. Serialization
Do you need to store complex variables or large text files in the database? Have you ever come up with a solution to fancy converting a formatted string array or object? Don't worry, PHP has already prepared this feature for us.

There are two methods of serialization, the following is an example, which uses serialize () to serialize and Unserialize () to de-serialize:

View sourceprint?01//a complex array

$myvar = Array (

' Hello ',

04 42,

Array (1, ' both '),

' Apple '

07);

A/convert to a string

$string = serialize ($myvar);

Echo $string;

One/* 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";}

13 */

//You can reproduce the original variable

$newvar = Unserialize ($string);

Print_r ($newvar);

+/* Prints

Array

19 (

[0] = = Hello

[1] = 42

[2] = = Array

23 (

[0] = 1

[1] =

26)

[3] = Apple

28)

29 */

This is the original eco-PHP serialization method. However, since JSON has been popular in recent years, PHP 5.2 has also decided to add support for them. You can now use the Json_encode () and Json_decode () functions to do the job:

View sourceprint?01//a complex array

$myvar = Array (

' Hello ',

04 42,

Array (1, ' both '),

' Apple '

07);

A/convert to a string

$string = Json_encode ($myvar);

Echo $string;

One/* Prints

["Hello", 42,[1, "I"], "apple"]

13 */

//You can reproduce the original variable

$newvar = Json_decode ($string);

Print_r ($newvar);

+/* Prints

Array

19 (

[0] = = Hello

[1] = 42

[2] = = Array

23 (

[0] = 1

[1] =

26)

[3] = Apple

28)

29 */

This will look more compact. Of course it is best for other languages such as JavaScript compatibility. However, you should note that for some complex objects, some information will be lost for no reason!

8. Compressing strings
When it comes to compression, we usually think of some files, such as zip files. It can compress long strings in PHP and does not involve any archive files.

In the following example, we will take advantage of the gzcompress () and Gzuncompress () functions:

View sourceprint?01 $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

Turpis sed tempor luctus. Curabitur sed nibh eu elit

Ten 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

22 */

echo "Compressed size:". Strlen ($compressed). " \ n ";

/* Prints

Compressed size:418

26 */

//Getting it back

$original = gzuncompress ($compressed);

We can compress nearly 50%. In addition Gzencode () and Gzdecode () can achieve similar results, but through different compression algorithms.

9. Register_shutdown_function
There is a function called register_shutdown_function (), which allows you to run the script before you have permission to execute some code.

Just imagine that you want to capture some of the baseline stats that your script executes to the end, such as how much time it takes to execute:

View Sourceprint?1//Capture the start time

2 $start _time = Microtime (true);

3//Do some stuff

4//...

5//Display How long the script took

6 echo "execution took:".

7 (Microtime (True)-$start _time).

8 "seconds.";

At first, these seemed trivial. You just add the code at the bottom and it runs before the script finishes. However, in the script where you call the exit () function, the code will not be executed. In addition, if there is a fatal error, or if the script is terminated by the user (by pressing the Stop button on the browser), refreshing the page again cannot be run.

When you use Register_shutdown_function (), your code will have no reason to be forced to stop:

View sourceprint?01 $start _time = Microtime (true);

Register_shutdown_function (' My_shutdown ');

//Do some stuff

04//...

function My_shutdown () {

_time Global $start;

"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.