4 Useful PHP Functions and Features You Need to Know

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.

First, here is an example with just optional arguments:

// function with 2 optional arguments
function foo($arg1 = '', $arg2 = '') {

    echo "arg1: $arg1\n";
    echo "arg2: $arg2\n";
}
foo('hello','world');
  /* prints:
  arg1: hello
  arg2: world
  */

foo();
/* prints:
arg1:
arg2:
*/

Now, 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():

// yes, the argument list can be empty
function foo() {
    // returns an array of all passed arguments
    $args = func_get_args();
    foreach ($args as $k => $v) {
        echo "arg".($k+1).": $v\n";
    }
}

foo();
/* prints nothing */
foo('hello');
  /* prints
  arg1: hello
  */
foo('hello', 'world', 'again');
/* prints
arg1: hello
arg2: world
arg3: again
*/

2. Using Glob() to Find Files

Many PHP functions have long and descriptive names. However it may be hard to tell what a function namedglob() does unless you are already familiar with that term from elsewhere.

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

You can fetch multiple file types like this:

// get all php files AND txt files
$files = glob('*.{php,txt}', GLOB_BRACE);
print_r($files);
/* output looks like:
Array
(
    [0] => phptest.php
    [1] => pi.php
    [2] => post_output.php
    [3] => test.php
    [4] => log.txt
    [5] => test.txt
)
*/

Note that the files can actually be returned with a path, depending on your query:

$files = glob('../images/a*.jpg');
print_r($files);
/* output looks like:
Array
(
    [0] => ../images/apple.jpg
    [1] => ../images/art.jpg
)
*/

If you want to get the full path to each file, you can just call the realpath() function on the returned values:

$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

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.

echo "Initial: ".memory_get_usage()." bytes \n";
/* prints
Initial: 361400 bytes
*/
// let's use up some memory
for ($i = 0; $i < 100000; $i++) {
	$array []= md5($i);
}
// let's remove half of the array
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";
/* prints
Peak: 13687072 bytes
*/

4. 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());
/* prints
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
  )
*/

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.

Let’s see an example:

// 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);
/* prints
User time: 0.011552
System time: 0
*/

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.

Here is another 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);
/* prints
User time: 1.424592
System time: 0.004204
*/

That took about 1.4 seconds of CPU time, almost all of which was user time, since there were no system calls.

System Time is the amount of time the CPU spends performing system calls for the kernel on the program’s behalf. Here is an example of that:

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

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.

Source: net.tutsplus.com

Dubai escorts
Nov 8, 2012

Howdy! I just want to give an enormous thumbs up for the great information you could have here on this post. I might be coming again to your blog for extra soon. wish you luck!

UAE escort
Nov 11, 2012

Great post. I was checking constantly this blog and I’m impressed! Extremely useful information specifically the last part :) I care for such info a lot. I was looking for this certain information for a long time. Thank you and best of luck. wish you luck!

escort girls Paris
Nov 16, 2012

I have discovered that good real estate agents almost everywhere are warming up to FSBO Marketing and advertising. They are knowing that it’s not only placing a sign post in the front property. It’s really concerning building associations with these dealers who someday will become buyers. So, while you give your time and efforts to helping these suppliers go it alone — the “Law involving Reciprocity” kicks in. Thanks for your blog post.

Sony HDR-CX740VE
Nov 22, 2012

Thanks for your publication. What I want to comment on is that while looking for a good internet electronics go shopping, look for a website with complete information on important factors such as the security statement, basic safety details, any payment guidelines, and other terms plus policies. Often take time to see the help and FAQ sections to get a greater idea of how the shop operates, what they can do for you, and exactly how you can take full advantage of the features. best wishes!

escort service Paris
Nov 28, 2012

Good write-up, I’m normal visitor of http://www.ushareweb.com , maintain up the nice operate, and It is going to be a regular visitor for a long time. wish you luck

vip escort dubai
Dec 13, 2012

I was recommended this website by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my problem. You are incredible! Thanks! regards

bur dubai escorts
Dec 13, 2012

I want to start a website where i can put google adds on, i have 10 dollars to spend and i know that isn’t a lot but it is better than those free websites that don’t let you do anything. so how do i get started?. wish you luck!

UAE escorts
Dec 14, 2012

That was some interesting stuff here on http://www.ushareweb.com Thanks for posting it.

escorts Dubai
Dec 14, 2012

This article on http://www.ushareweb.com gives the light in which we can observe the reality.

escorts France
Dec 14, 2012

Bonjour http://www.ushareweb.com. J’ai trouvé votre site Web via Google tout en recherchant une affaire semblable, votre site web arrivé ici en place. Il semble bon. J’ai un signet dans mon google bookmarks de revenir plus tard.

dubai model escort
Jan 29, 2013

Nice! Just wanted to respond. I thoroughly loved your post. Keep up the great work on http://www.ushareweb.com .

escort girls Kuwait
Feb 2, 2013

What can be the ideal Joomla template for a magazine or feature wire service?

sustanon
Feb 22, 2013

I can?t believe your web blog could be so mind blowing and epistemlogically significant nevertheless I?ll alert my other friends , relatives, and significant others thanks and not let your self-esteem be lowered when you are a fantastic individual!!

escrte girl
Mar 13, 2013

I was also reading a topic like this one from another site..~:.:

esort girl
Mar 19, 2013

Hey there! Nice stuff, do keep me posted when you post again something like that!

escortes girl
Mar 19, 2013

Hello! Would you mind if I share your blog with my twitter group? There?s a lot of folks that I think would really appreciate your content. Please let me know. Many thanks

escort France
Mar 21, 2013

Thank you, wonderful job! Just the thing I needed to get.

excorte girl
Mar 28, 2013

Greetings from Los angeles! I?m bored to tears at work so I decided to browse your site on my iphone during lunch break. I really like the knowledge you present here and can?t wait to take a look when I get home. I?m shocked at how quick your blog loaded on my phone .. I?m not even using WIFI, just 3G .. Anyways, amazing blog!

escortes France
Apr 7, 2013

You have brought up a very good points , thanks for the post.

Combien de billet de blog que je devrais avoir avant de commencer sa promotion ? Cordialement!

Nice escorted
Apr 18, 2013

This is the proper weblog for anybody who desires to seek out out about this topic. You realize so much its almost hard to argue with you (not that I truly would need?HaHa). You positively put a new spin on a topic thats been written about for years. Nice stuff, just great!

escorts France
Apr 18, 2013

Sinon, ça consiste en quoi au juste, l’effeuillage d’harmonica ?

I’ve learn several good stuff here. Definitely worth bookmarking for revisiting. I surprise how a lot attempt you put to create such a wonderful informative site. ;) ;)

scorte girl
Apr 30, 2013

Thanks , I have just been searching for info about this subject for ages and yours is the best I?ve discovered till now. But, what about the bottom line? Are you sure about the source?

escorte Paris
May 1, 2013

Strange , this page shows up with a dark hue to it, what color is the primary color on your site?

Google
May 25, 2013

Google…

Always a big fan of linking to bloggers that I really like but don’t get a lot of link like from….

Anabol 10
Jun 5, 2013

I admit, I have not been on http://www.ushareweb.com in a long time however it was another joy to see It is such an important topic and ignored by so many, even professionals. I thank you to help making people more aware of possible issues.

Homepage
Jun 17, 2013

… [Trackback]…

[...] Find More Informations here: ushareweb.com/4-useful-php-functions-and-features-you-need-to-know/225 [...]…

anabolika shop
Aug 31, 2013

I Really enjoyed your blog. I just bookmarked it. I am a regular visitor of your website I will share It with Yep. I lurk there often. You guys have a wonderful blog. Keep up the good work.. Its hard to find knowledgeable individuals on this matter, bu…










*