Home Backend Development PHP Tutorial 8 essential PHP functions for development

8 essential PHP functions for development

Aug 08, 2016 am 09:33 AM
nbsp php

Programmers who have done PHP development should know that there are many built-in functions in PHP. Mastering them can help you become more comfortable in PHP development. This article will share 8 essential PHP functions for development, all of which are very useful. Practical, I hope all PHP developers can master it.

 1. Pass any number of function parameters

 In .NET or JAVA programming, the number of function parameters is generally fixed, but PHP allows you to use any number of parameters. The following example shows you the default parameters of a PHP function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Function with two default parameters
function foo($arg1 = ”, $arg2 = ”) {
echo "arg1: $arg1n";
echo "arg2: $arg2n";
}
foo(‘hello’,’world’);
/* Output:
arg1: hello
arg2: world
*/
foo();
/* Output:
arg1:
arg2:
*/

The following example is the usage of variable parameters in PHP, which uses the ?func_get_args() method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Yes, the formal parameter list is empty
function foo() {
// Get the array of all incoming parameters
$args = func_get_args();
foreach ($args as $k => $v) {
echo "arg".($k+1).": $vn";
}
}
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

 The function names of most PHP functions can understand their purpose literally, but when you see ?glob(), you may not know what it is used for. In fact, glob() and scandir() Same, it can be used to find files, please see the usage below:

1
2
3
4
5
6
7
8
9
10
11
12
13
// Get all files with the suffix 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 search for a variety of suffixes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Get PHP files 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 path:

1
2
3
4
5
6
7
8
9
10
$files = glob(‘../images/a*.jpg’);
print_r($files);
/* Output:
Array
(
[0] => ../images/apple.jpg
[1] => ../images/art.jpg
)
*/

 If you want to get the absolute path, you can call the ?realpath() function:

1
2
3
4
5
6
7
8
9
10
11
12
13
$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:wampwwwimagesapple.jpg
[1] => C:wampwwwimagesart.jpg
)
*/

 3. Get memory usage information

  PHP’s memory recycling mechanism is already very powerful. You can also use PHP scripts to obtain the current memory usage. Call the memory_get_usage() function to obtain the current memory usage, and call the memory_get_peak_usage() function to obtain the peak memory usage. The reference code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
echo “Initial: “.memory_get_usage().” bytes n”;
/* output
Initial: 361400 bytes
*/
//Use memory
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

Peak: 13687072 bytes

*/

 4. Get CPU usage information

 After obtaining the memory usage, you can also use PHP's getrusage() to obtain the CPU usage. This method is not available under Windows.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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 very obscure, unless you know the CPU very well. Here are some explanations:

  • ru_oublock: block output operation
  • ru_inblock: block input operation
  • ru_msgsnd: message sent
  • ru_msgrcv: message received
  • ru_maxrss: Maximum resident set size
  • ru_ixrss: total shared memory size
  • ru_idrss: All non-shared memory size
  • ru_minflt: Page recycling
  • ru_majflt: Page invalid
  • ru_nsignals: Received signals
  • ru_nvcsw: Active context switching
  • ru_nivcsw: Passive context switching
  • ru_nswap: Swap area
  • ru_utime.tv_usec: User mode time (microseconds)
  • ru_utime.tv_sec: User mode 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". The seconds and microseconds parts are provided separately. You can divide the microseconds value by 1 million and add it to the seconds value to get the fractional seconds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 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 system time. We can look at the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 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 was user time since there were no system calls.

 System time is the time the CPU spends executing kernel instructions on system calls. Here is an example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

$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. Get system constants

  PHP provides very useful system constants that allow you to get the current line number (__LINE__), file (__FILE__), directory (__DIR__), function name (__FUNCTION__), class name (__CLASS__), method name (__METHOD__) and namespace (__NAMESPACE__), much like C language.

 We can think that these things are mainly used for debugging, but that is not necessarily the case. For example, we can use ?__FILE__ when including other files (of course, you can also use __DIR__ after PHP 5.3). Here is an example.

1

2

3

4

5

6

7

// 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 is using __LINE__ to output some debug information, which will help you debug the program:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

// 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: $msgn";

}

 6. Generate unique id

Many friends use md5() to generate unique numbers, but md5() has several shortcomings: 1. Disorder, which leads to a decrease in sorting performance in the database. 2. Too long and requires more storage space. In fact, PHP comes with a function to generate a unique id. This function is uniqid(). Here’s how to use it:

1

2

3

4

5

6

7

8

9

10

11

// generate unique string

echo uniqid();

/* output

4bd67c947233e

*/

// generate another unique string

echo uniqid();

/* output

4bd67c9472340

*/

 This algorithm is generated based on CPU timestamps, so in a similar time period, the first few digits of the ID are the same, which also facilitates the sorting of IDs. If you want to better avoid duplication, you can add before the ID Prefix, such as:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

// prefix

echo uniqid(‘foo_’);

/* output

foo_4bd67d6cd8b8f

*/

// There is more entropy

echo uniqid(”,true);

/* output

4bd67d6cd8b926.12135106

*/

// It’s all there

echo uniqid(‘bar_’,true);

/* output

bar_4bd67da367b650.43684647

*/

 7. Serialization

  PHP serialization function may be used more and more commonly. When you need to save data to a database or file, you can use the serialize() and unserialize() methods in PHP to achieve serialization and deserialization. ization, the code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

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

*/

//Deserialization

$newvar = unserialize($string);

print_r($newvar);

/* output

Array

(

[0] => hello

[1] => 42

[2] => Array

(

[0] => 1
[1] => two
)
[3] => apple
)
*/

How to serialize into json format? Don’t worry, PHP has already done it for you. Users using PHP 5.2 or above can use the json_encode() and json_decode() functions to serialize json format. The code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
$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";
/* Output original size
Original size: 800
*/
echo "Compressed size: ". strlen($compressed)."n";
/* Output the compressed size
Compressed size: 418
*/
//Decompress
$original = gzuncompress($compressed);

 Almost 50% compression ratio. At the same time, you can also use the ?gzencode() and gzdecode() functions to compress, just using different compression algorithms.

The above are 8 essential PHP functions for development. Are they all practical?

The above introduces 8 PHP functions that are necessary for development, including related content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles