Useful PHP Functions and Features You Need to Know



Functions with Arbitrary Number of Arguments

let's see how we can build a function that accepts any number of arguments. This time we are going to utilize func_get_args():
use $args = func_get_args(); inside the function.

Using Glob() to Find Files

Think of it like a more capable version of the scandir() function. It can let you search for files by using patterns.
// get all php files
$files = glob('*.php');
print_r($files);
/* output looks like:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
)
*/

Memory Usage Information

can use the memory_get_usage() function, and to get the highest amount of memory used at any point, we can use the memory_get_peak_usage() function.

CPU Usage Information

For this, we are going to utilize the getrusage() function. Keep in mind that this is not available on Windows platforms.
print_r(getrusage());
That may look a bit cryptic unless you already have a system administration background. Here is the explanation of each value (you don't need to memorize 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)

Magic Constants

PHP provides useful magic constants for fetching the current line number (__LINE__), file path (__FILE__), directory path (__DIR__), function name (__FUNCTION__), class name (__CLASS__), method name (__METHOD__) and namespace (__NAMESPACE__).

Generating Unique ID's

There may be situations where you need to generate a unique string. I have seen many people use themd5() function for this, even though it's not exactly meant for this purpose:
// generate unique string
echo md5(time() . mt_rand(1,1000000));
There is actually a PHP function named uniqid() that is meant to be used for this.
echo uniqid('bar_',true);
/* prints bar_4bd67da367b650.43684647*/

Compressing Strings

When talking about compression, we usually think about files, such as ZIP archives. It is possible to compress long strings in PHP, without involving any archive files.

In the following example we are going to utilize the gzcompress() and gzuncompress() functions.

// gzcompress a string
$compressed = gzcompress('Compress me', 9);
echo $compressed."<br />";
// gzuncompress a string
$uncompressed = gzuncompress($compressed);
echo $uncompressed."<br />";
?>



Comments

Popular posts from this blog

Byobu : Japanese term for decorative