9 Useful PHP Functions and Features You Need to Know

Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Nettuts+.

Even after using PHP for years, we stumble upon functions and features that we did not know about. Some of these can be quite useful, yet underused. With that in mind, I've compiled a list of nine incredibly useful PHP functions and features that you should be familiar with.

1. Functions with Arbitrary Number of Arguments

You may already know that PHP allows you to define functions with optional arguments. But there is also a method for allowing completely arbitrary number of function arguments.

3. Memory Usage Information

By observing the memory usage of your scripts, you may be able optimize your code better.

PHP has a garbage collector and a pretty complex memory manager. The amount of memory being used by your script. can go up and down during the execution of a script. To get the current memory usage, we 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.

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)

To see how much CPU power the script has consumed, we need to look at the 'user time' and 'system time' values. The seconds and microseconds portions are provided separately by default. You can divide the microseconds value by 1 million, and add it to the seconds value, to get the total seconds as a decimal number.

Even though the script took about 3 seconds to run, the CPU usage was very very low. Because during the sleep operation, the script actually does not consume CPU resources. There are many other tasks that may take real time, but may not use CPU time, like waiting for disk operations. So as you see, the CPU usage and the actual length of the runtime are not always the same.

Now we have quite a bit of system time usage. This is because the script calls the microtime() function many times, which performs a request through the operating system to fetch the time.

Also you may notice the numbers do not quite add up to 3 seconds. This is because there were probably other processes on the server as well, and the script was not using 100% CPU for the whole duration of the 3 seconds.

5. 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__).

We are not going to cover each one of these in this article, but I will show you a few use cases.

When including other scripts, it is a good idea to utilize the __FILE__ constant (or also __DIR__ , as of PHP 5.3):

// 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 __LINE__ makes debugging easier. You can track down the line numbers:

You may notice that even though the strings are unique, they seem similar for the first several characters. This is because the generated string is related to the server time. This actually has a nice side effect, as every new generated id comes later in alphabetical order, so they can be sorted.

To reduce the chances of getting a duplicate, you can pass a prefix, or the second parameter to increase entropy:

This function will generate shorter strings than md5(), which will also save you some space.

7. Serialization

Have you ever needed to store a complex variable in a database or a text file? You do not have to come up with a fancy solution to convert your arrays or objects into formatted strings, as PHP already has functions for this purpose.

This was the native PHP serialization method. However, since JSON has become so popular in recent years, they decided to add support for it in PHP 5.2. Now you can use the json_encode() and json_decode() functions as well:

At first this may seem trivial. You just add the code to the very bottom of the script and it runs before it finishes. However, if you ever call the exit() function, that code will never run. Also, if there is a fatal error, or if the script is terminated by the user (by pressing the Stop button in the browser), again it may not run.

When you use register_shutdown_function(), your code will execute no matter why the script has stopped running: