Nine php functions and features that you need to know to be useful

  • 2020-08-22 21:55:54
  • OfStack

Here are 9 PHP features that are very useful. Have you used them?
1. Any number of arguments to a function
You may know that PHP allows you to define a function with 1 default argument. But you may not know that PHP also allows you to define a function with a completely arbitrary parameter
Here is an example of a function that shows you the default parameters:


//  Function with two default arguments  
function foo($arg1 = '', $arg2 = '') { 

    echo "arg1: $arg1/n"; 
    echo "arg2: $arg2/n"; 

} 

foo('hello','world'); 
/*  The output : 
arg1: hello 
arg2: world 
*/

foo(); 
/*  The output : 
arg1: 
arg2: 
*/

Now let's look at 1 for a function with an indefinite argument, using the func_get_args() method:

//  Yes, the parameter list is empty  
function foo() { 

    //  Gets an array of all the parameters passed in  
    $args = func_get_args(); 

    foreach ($args as $k => $v) { 
        echo "arg".($k+1).": $v/n"; 
    } 

} 

foo(); 
/*  Nothing will be exported  */

foo('hello'); 
/*  The output  
arg1: hello 
*/

foo('hello', 'world', 'again'); 
/*  The output  
arg1: hello 
arg2: world 
arg3: again 
*/


2. Find the file using Glob()
Many PHP functions have a long self-explanatory function name, but when you look at glob(), you may not know what the function is for unless you are already familiar with it.

You can think of this function as scandir() 1, which can be used to find files.

//  Get all suffixes as PHP The file  
$files = glob('*.php'); 

print_r($files); 
/*  The output : 
Array 
( 
    [0] => phptest.php 
    [1] => pi.php 
    [2] => post_output.php 
    [3] => test.php 
) */
 You can also look up a variety of suffix names 
//  take PHP Files and TXT file  
$files = glob('*.{php,txt}', GLOB_BRACE); 

print_r($files); 
/*  The 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 paths:

$files = glob('../images/a*.jpg'); 

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

If you want the absolute path, you can call the 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. Memory usage information
Observing your program's memory usage can help you optimize your code better.
PHP has a garbage collection mechanism and has a very complex memory management mechanism. You can find out how much memory your script is using. To know the current memory usage, you can use the memory_get_usage() function, and if you want to know the peak memory usage, you can call the memory_ge

ak_usage() function.

echo "Initial: ".memory_get_usage()." bytes /n"; 
/*  The output  
Initial: 361400 bytes 
*/

//  The use of memory  
for ($i = 0; $i < 100000; $i++) { 
    $array []= md5($i); 
} 

//  delete 1 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"; 
/*  The peak output  
Peak: 13687072 bytes 
*/

4. CPU Usage information
Using the getrusage() function will let you know how CPU is being used. Note that this feature is not available under Windows.

print_r(getrusage()); 
/*  The 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 is structurally obscure unless you know CPU 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: Total non-shared memory size
ru_minflt: recycling
ru_majflt: failure
ru_nsignals: Signal received
ru_nvcsw: Active context switch
ru_nivcsw: Passive context switch
ru_nswap: swap
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 sections are provided separately, and you can divide the microseconds value by 1 million and add it to the seconds value to get the number of seconds with a fractional 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); 

/*  The output  
User time: 0.011552 
System time: 0 
*/

sleep does not take up system time. Here is an 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); 

/*  The output  
User time: 1.424592 
System time: 0.004204 
*/

This took about 14 seconds of CPU, almost all of the user's time, because there were no system calls.
System time is the time that CPU spends executing kernel instructions on system calls. 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 
*/

We can see that the above example is even more expensive than CPU.

5. System constants
PHP provides very useful system constants that let you get the current row number (142EN__), file (143en__), table of contents (144en__), function name (145en__), class name (146en__), method name (147en__) and namespace (148en__), much like the C language.

We can assume that these things are mainly used for debugging, but not necessarily when, for example, we can use them with other include files, right? ___ (Of course, you can also use ___ after PHP 5.3 with each ___.


// 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');

Using ___, 159EN__ to output 1 of debug to help you debug the programme:

// some code 
// ... 
my_debug("some debug message", __LINE__); 
/*  The output  
Line 4: some debug message 
*/

// some more code 
// ... 
my_debug("another debug message", __LINE__); 
/*  The output  
Line 11: another debug message 
*/

function my_debug($msg, $line) { 
    echo "Line $line: $msg/n"; 
}

6. Generate ID with only 1
Many people use md5() to generate a one-only ID, as shown below:
// generate unique string
echo md5(time() . mt_rand(1,1000000));
In fact, one of the PHP functions called uniqid() is dedicated to this:

// generate unique string 
echo uniqid(); 
/*  The output  
4bd67c947233e 
*/

// generate another unique string 
echo uniqid(); 
/*  The output  
4bd67c9472340 
*/

You may notice that the first bits of ID generated are one, because the generator depends on the time of the system, which is actually a very nice feature because you can easily sort your ID. You can't do this with MD5.
You can also prefix it to avoid duplicate names:

//  The prefix  
echo uniqid('foo_'); 
/*  The output  
foo_4bd67d6cd8b8f 
*/

//  There's more entropy  
echo uniqid('',true); 
/*  The output  
4bd67d6cd8b926.12135106 
*/

//  There are  
echo uniqid('bar_',true); 
/*  The output  
bar_4bd67da367b650.43684647 
*/

Also, ID will be shorter than MD5, which will save you a lot of space.

7. The serialization
Do you save a complex data structure to a database or file? You don't have to write your own algorithm. PHP is already there for you, providing two functions: serialize() and unserialize():


// 1 It's a complex array  
$myvar = array( 
    'hello', 
    42, 
    array(1,'two'), 
    'apple'
); 

//  serialization  
$string = serialize($myvar); 

echo $string; 
/*  The 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";} 
*/

//  Antitone instantiated  
$newvar = unserialize($string); 

print_r($newvar); 
/*  The output  
Array 
( 
    [0] => hello 
    [1] => 42 
    [2] => Array 
        ( 
            [0] => 1 
            [1] => two 
        ) 

    [3] => apple 
) 
*/

This is the native function of PHP, however JSON is becoming more and more popular today, so after ES198en 5.2, PHP supports JSON, you can use the json_encode() and json_decode() functions

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

This looks a bit more compact and is compatible with Javascript and other languages. However, for some very complex data structures, data loss may occur.

String compression
When we talk about compression, we might think of file compression, but strings can also be compressed. PHP provides 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"; 
/*  Output original size  
Original size: 800 
*/

echo "Compressed size: ". strlen($compressed)."/n"; 
/*  Output size after compression  
Compressed size: 418 
*/

//  unzip  
$original = gzuncompress($compressed);

It's almost 50 percent compression. You can also compress using the gzencode() and gzdecode() functions, but not using different compression algorithms.

9. Register the stop function
There is a function called register_shutdown_function() that lets you run the code before the entire script stops. Let's look at the following example:


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

The above example is simply used to calculate the running time of a function. Then, if you call the exit() function in the middle of the function, your final code will not be run to. Also, if the script terminates in the browser (the user presses the stop button), it cannot be run.
And when we use register_shutdown_function(), your program will run even after the script is stopped:

//  Yes, the parameter list is empty  
function foo() { 

    //  Gets an array of all the parameters passed in  
    $args = func_get_args(); 

    foreach ($args as $k => $v) { 
        echo "arg".($k+1).": $v/n"; 
    } 

} 

foo(); 
/*  Nothing will be exported  */

foo('hello'); 
/*  The output  
arg1: hello 
*/

foo('hello', 'world', 'again'); 
/*  The output  
arg1: hello 
arg2: world 
arg3: again 
*/
8


Related articles: