Try Tuts+ Premium, Get Cash Back!
9 Useful PHP Functions and Features You Need to Know

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.

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 named glob() 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.


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:

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

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

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

6. Generating Unique ID's

There may be situations where you need to generate a unique string. I have seen many people use the md5() 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.

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

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

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:

// with prefix
echo uniqid('foo_');
/* prints
foo_4bd67d6cd8b8f
*/

// with more entropy
echo uniqid('',true);
/* prints
4bd67d6cd8b926.12135106
*/

// both
echo uniqid('bar_',true);
/* prints
bar_4bd67da367b650.43684647
*/

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.

There are two popular methods of serializing variables. Here is an example that uses the serialize() and unserialize():

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

// convert to a string
$string = serialize($myvar);

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

// you can reproduce the original variable
$newvar = unserialize($string);

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

    [3] => apple
)
*/

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:

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

It is more compact, and best of all, compatible with javascript and many other languages. However, for complex objects, some information may be lost.


8. 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:

$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";
/* prints
Original size: 800
*/
echo "Compressed size: ". strlen($compressed)."\n";
/* prints
Compressed size: 418
*/

// getting it back
$original = gzuncompress($compressed);

We were able to achive almost 50% size reduction. Also the functions gzencode() and gzdecode() achive similar results, by using a different compression algorithm.


9. Register Shutdown Function

There is a function called register_shutdown_function(), which will let you execute some code right before the script finishes running.

Imagine that you want to capture some benchmark statistics at the end of your script execution, such as how long it took to run:

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

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:

$start_time = microtime(true);

register_shutdown_function('my_shutdown');

// do some stuff
// ...
function my_shutdown() {
	global $start_time;

	echo "execution took: ".
			(microtime(true) - $start_time).
			" seconds.";
}

Conclusion

Are you aware of any other PHP features that are not widely known but can be quite useful? Please share with us in the comments. And thank you for reading!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://blog.creative-webdesign.info Andi

    Some good advices. I like your tutorials!

  • http://japh.com.au/ Japh

    Great article, thanks for the convenient listing :)

    I think it should be mentioned, that as with any function, it’s important to be sure you’re using the right one for your situation.

    The serialize() and unserialize() functions can give quite a performance hit if used too liberally or if forced to serialize very large amounts of information.

    I recently ran into problems with an intensive page taking upwards of 40 seconds to load on account of trying to serialize multiple large objects instead of just their ID.

    Here’s another interesting read on comparing performance:
    http://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize

  • Dylan

    It should be noted that #6 does not produce GUARANTEED unique strings, just strings that are highly probably unique – in the same way that MD5 doesn’t produce a guaranteed unique hash for a given string.

    • http://japh.com.au/ Japh

      Good point! And to reduce the likelyhood of creating duplicates, something more robust than MD5 could be used, such as SHA1, which has fewer collisions.

      • Dylan

        True, though any hashing function that has a finite hash-space (if that’s the right term) will always have the possibility of duplicates.

        To remove the possibility of duplicates, you have to store previously given unique ids & check against that list, when giving out new ids.

      • Patrick

        MD5 collision… This is one of that myths, that doesn’t matter for most of all webdevs i think. I’ve never ever produced an MD5 collision…

      • Patrick

        Ah, and btw, i don’t use MD5 for generating an unique id. I use this:

        function uniqueKey($length = “32″)
        {
        $uniquekey =”";
        $code = array_merge(range(’0′, ’9′), range(‘a’, ‘z’), range(‘A’, ‘Z’));
        mt_srand((double)microtime()*1000000);
        if($length > 1024): $length = “1024″;endif;
        for ($i = 1; $i <= $length; $i++)
        {
        $swap = mt_rand(0,count($code)-1);
        $uniquekey .= $code[$swap];
        }
        return $uniquekey;
        }

    • http://www.phphorizons.com Floydian

      uniqid() produces a universally unique id or a globally unique id. If one were to run this function once, for every second the universe has been in existence, you would have a very low chance of producing a collision (especially when using more entropy).

      Assuming a 13.5 billion year age for the universe, that’s 425,736,000,000,000,000 seconds or 425.7e15.
      Now, without entropy, we have 13 characters which can be letters or numbers giving 36 possibilities. That gives us 36e13 possibilities or 170,581,728,179,578,208,256. Factoring in 9 decimal places of numbers 0 to 9 gives us a multiplication factor of 1 billion – 1 increasing the total number of possible ids to:

      1.26+49

      That is so large, that producing a collision would be like winning the lottery 10 times in a row. I doesn’t happen, basically.

      Cheers

      • http://arturoguzman.ca Arturo

        That’s some nice theory, but that is based on the fact that the uniqid() algorithm is in fact producing ‘random’ characters.

        Anyway, I do agree that uniqid or md5 collissions shouldn’t keep you awake at night, has somebody ever had a collision? Maybe it’s a job for the Mythbusters…

      • http://blogs.meronepalma.com acpmasquerade

        uniqid is restricted to a server only, there isn’t something like it generates the universally unique id. however there are few tricks we can use to identify almost universally unique ID. Its just a way, please comment later.

        Following parameters can be used as unique identifiers for any server.
        a) IP Address
        b) Hostname
        c) Current Timestamp

        so prefixing a string with these three parameters and generating a unique id using the php function uniqueid() will generate almost universally unique id.

        Example Code:

      • http://blogs.meronepalma.com acpmasquerade

        In my earlier post there was the example php code, but it got truncated.

        For moderator, please include the code replacing with htmlentities.

    • http://www.phpandstuff.com/ Burak
      Author

      Collision with the uniqid function is highly unlikely, especially if you pass the second parameter.

      The only downside is that it has predictable values. You can make close guesses to what range of values would be generated at any given time, because it is based on the server clock.

  • http://xpressabhi.com abhishek

    Nice article..
    I am writing a php page for redirecting urls on some conditions. I got your article on time.

  • Patrick

    func_get_args is a nice feature, but i think it could be a huge security risk. I think it’s always better to know that functions use only the fixed given params.

    uniqueid is also a nice feature, BUT: Don’t use it safety-critical things! Every hacker would love you if you use this function for sessions or something like that.

    register_shutdown_function is one of the best functions explained in here. Perfect to catch each script abort.

    • Mark

      Patrick, the security risk is the same as a function with a set number of arguments. They’re both dependent on the programmer and how he handles the parameters. Although setting the parameters for a method or function is always preferred, there are some cases where allowing for any number of parameters is the best solution for a problem.

      You will see this implemented in some core PHP functions: register_shutdown_function(), array_merge(), var_dump(), …

    • Abhijit

      I am Drupal developer and I see that Drupal does use functions with variable number of arguments. I don’t think func_get_args can be a big security risk. Also PHP functions like printf(), sprintf() (and many others) also arbitrary number of arguments. Allowing variable number arguments can be quite handy at times.

      • Abhijit

        Sorry for some grammatical mistakes in my above comment

      • Patrick

        Yeah, i know about the advantages of this function. Perhaps it don’t might be a high security risk, but, what if a module dev use an important function of drupal which use variable arguments and fill them with unexpected values? Okay, i actually don’t think drupal has no validation routines, but what if the function don’t have one?

        I think func_get_args could result in more work than fixed arguments, because only here you know what you have… But, i don’t say it’s a bad function, as you say it could be quite handy ;)

        bzw – don’t worry about your writing… I’m even not better^^

      • http://twitter.com/nine_l Lenin

        Liked the article it will help newbies and even mid-level programmers to look around for more functions. Expect more advanced level articles from you too.

        @Abhijit: We Asians are much more grammar sensitive than the native speakers of English are ;)

  • John

    PHP sucks !

    Start using Asp.Net !

    • Shiro

      Maybe can you show some asp.net awesome feature, rather then, just say sucks, else just shut up

    • Joe Schmoe

      Sure, I’ll use it… when Microsoft, Google, Apple, and IBM all merge into one super company. ;)

    • Arturo

      Amazing insight!

    • http://www.mcbwebdesign.co.uk/ MCB Web Design

      Fantastic that ‘John’ takes the time to read PHP-related articles any way…

      • http://jfoucher.fr Jonathan Foucher

        He should have signed ‘Bill’, though ;)

    • http://michaeljeromeoher.com/ Michael Oher

      Absolutely I Agree !!

    • Ken

      Time to hop on the Web Objects / Eclipse / Java bandwagon! ASP.NET doesn’t hold a candle to WO, just ask Apple.

      PHP is an amazing Scripting language, but I agree that there are some limitations, such as maintaining state through the life of the application (SESSION is not really state maintenance).

      Bottom line, PHP is free, easy, well-documented, available on almost all platforms and these functions are great!

      Keep up the good work Burak!

  • David Runion

    register_shutdown_function is a useful tool, but I prefer ob_start(). I set it up in a file called via auto_prepend_file so that it runs on each and every page.

    ob stands for output buffering. It means that the HTML page isn’t sent until after the script has finished. Instead of outputting PHP-parsed HTML as it is parsed, it is “buffered” and then sent all at once. This actually has performance benefits unless your script takes forever to run, because the HTML can be sent at once rather than peacemeal.

    The main reason for using it is to run a shutdown function, however. I do:

    if(defined(‘LOGGEDIN’) && LOGGEDIN) {
    ob_start(‘addPartnerScripts’);
    }

    and then

    ob_start(‘shutdown_func’);

    function addPartnerScripts($buffer) {
    if(stripos($buffer, “”) !== FALSE) {
    /*in here, I string-replace in $buffer with my javascript functions that logged in partners can utilize. */
    }
    return $buffer
    }

    shutdown_func is similar but I use it to put analytics code into every page. I needed to do that because I have different “languages” that the pages are in that I want to track separately.

    There are tons of other things you can do with a shutdown function that runs on every PHP file and gets passed all the already-PHP-parsed HTML and allows you to modify it before it is sent to the client. Heck, somebody ought to write a tut on this!

    • David Runion

      Above, I had a closing body tag that was stripped out inside of the quotes seen here:

      stripos($buffer, “”)

      I replace [/body] with scripts+[/body] before sending the HTML to the client.

  • http://www.phpmycoder.net PhpMyCoder

    Wouldn’t this code remove ALL of the elements in the array since the first loop created 10000 elements:

    —-
    // let’s remove half of the array
    for ($i = 0; $i < 100000; $i++) {
    unset($array[$i]);
    }
    —-

    Shouldn't it be:

    —-
    // let's remove half of the array
    for ($i = 0; $i < 50000; $i++) {
    unset($array[$i]);
    }
    —-

    • http://www.phpandstuff.com/ Burak
      Author

      Yea, I thought I wrote 500000. Thanks for catching that.

  • http://ds.laroouse.com esranull

    Nice article.. thanks lot

  • http://www.deluxeblogtips.com Deluxe Blog Tips

    Cool article. Most of them are new and very interesting to me. I see that WordPress maybe uses the serialize function to store its options. The function func_get_args() looks like in Javascript. Thank you so much for this.

  • http://codeigniter-tutorial.com CodeIgniter Tutorial

    Thanks Burak, I didn’t know about glob() . By the way, will the CI From Scratch series continue ?

    Good luck!

  • http://spotdex.com Davidmoreen

    I learned about the func_get_args() function last week. I haven’t stopped using it since! Also the Magic Constants are indeed magic!

  • http://protishobdo.com Maz

    Nice tut. Thanks!

  • http://bipin.me bipin karmacharya

    Thanks author!! indeed nice list of the functions reducing number of lines of code!!!

  • http://kodegeek.wordpress.com Musa

    I like most register_shutdown_function, its easy to know few unknown function here. it would be great if include some magic functions here.

    Thanks

  • J W

    Very good tutorial, I like your clean samples!

  • umut

    cool staff thx

  • Kuboslav

    Thanks a lot Burak .. another one great and useful tutorial. And what’s about Codeigniter form scratch tutorials ? I think something about caching would be useful ..

  • http://xo66ut.ru/ Xo66uT

    Good features, some of them was interesting, thanks for it.

  • http://www.webmasterdubai.com webmasterdubai

    very nice article and i like one function gzcompress really nice but work good for utf-8 language i have tried on Arabic it gives some odd chars

  • http://livelyworks.net/ LivelyWorks

    Thanks for such useful & great article.

  • http://www.tariqit.com Tariq

    Great post Thanks for such important and useful functions.

  • http://www.gostomski.co.uk Damian Jakusz-Gostomski

    Wow, some awesome gooodness here as always. I knew about 1, 3, 5 and 7 and they are the sort of things that change the way you work when you discover them

  • http://www.qap.pl/ Krzysztof Malisiewicz

    __METHOD__ saves me a lot of time with debug. Thanks for that.

  • http://www.iconfinder.com Martin LeBlanc Eigtved

    Thanks a lot for this post. Even after years of experience with PHP you can always learn new stuff.
    Retweeted!

  • http://www.gamesoid.com Alice Havelock

    Hey Buddy Thanks for Such fantastic functions i love to use it…

  • Márcio Almada

    Thanks for that awesome article!!

  • http://www.jsxtech.com Jaspal Singh

    Thanks Burak, nice tutorial.
    I really like – register_shutdown_function() and glob() function.

  • Ümit Ünal

    Thanks Burak,
    Very Nice tutorial.

  • http://www.jordanwalker.net Jordan Walker

    Nice article, very informative.

  • paul

    instantly helpful! awsome.

    please please more php tutorials…

  • http://TechCline.com saad irfan

    Awesome. thx for sharing it man…. really helpful….

  • http://andrewensley.com/ Andrew

    Thanks for the great article. Good tips. I was really interested in #4, but it’s not working for me.

    I copied your code exactly, but my results were wildly different. User time was never under 15 seconds even though the scripts always executed within 3 seconds. There doesn’t seem to be any rhyme or reason to the results.

    I’ve created a question on StackOverflow about it, but I wondered if you had any thoughts as to what could be going wrong.

  • http://stevelove.org Steve Love

    There’s been some interest in the glob() function the last few days. It was mentioned in NetTuts and today Bill Karwin on PHP Architect attempted to do some benchmarking. The results showed that the ease of using glob() may not be worth the performance hit:

    “Of course it’s desirable to write concise code, but don’t assume this always equates to fast code. Rapid development and rapid code are independent goals, and you need to decide which has greater priority on a case-by-case basis.” – Bill Karwin

  • Koen

    PHP isnt exactly Lisp, but you can do some pretty cool dynamic programming.

    For example you can call variables by their name.

    $x = 42;
    $varName = a;
    echo $$varName; // prints 42, note the double $

    The same goes for functions:

    function getNumber() {
    return 42;
    }

    $funName = getNumber;
    echo $funName(); // prints 42

    You can also construct anonymous functions on the fly with create_function():

    $fun = create_function(, return 42;);
    echo $fun(); // prints 42

    Note that create_function() is pretty slow. You can usually reach the same result by passing a different predefined function (or rather its name, strictly speaking) to another predefined function. For example, you might have one function that iterates a data structure, which you pass a function that defines what to do with every item in that structure.

  • Koen

    In case anybodys confused, that first piece of PHP should be:

    $x = 42;
    $varName = ‘x;
    echo $$varName; // prints “42″, note the double $

  • http://www.sisnolabs.com Sachin

    very useful for PHP programmers. it will help to minimize the code the way we used code in php4.

    looking forward for more php tips on coming posts. cheers.

  • http://www.electrictoolbox.com Chris Hope

    Just a quick note about the memory_get_usage() function. It is always available from PHP 5.2.1 but prior to that (4.3.2+) required the –enable-memory-limit flag at compile time. If you are running on a version of PHP before 5.2.1 it may not be available.

  • http://www.searchengineoptimization.co.uk Mike

    This is nice article, thanks for the same…i was looking for any php function which tells me about how many SSH are open for website in Linux Server, i have habit of opening SSH for a website to do install work of scripts and keep them opened….

    So if you can give me any quick function, script or command to check how many SSH are open for apache web sites, it will be nice, good that i run single script on the shell and comes to know the details

    • http://www.phpandstuff.com/ Burak
      Author

      That might be something you need to do using shell commands. From PHP you can execute shell commands and get the results by using the shell_exec() function.

  • http://www.ertankayalar.com.tr ertan

    thanks burak, nice article. I like glob() function.

  • http://blog.ashfame.com Ashfame

    I get to learn a quite few of those. Thanks! I like these – “you don’t know” tutorials :)

  • http://www.kotlarski.net Krzysztof Kotlarski

    Very nice tut.
    __destruct() can be nice replacement for register_shutdown_function() when more than one function is needed (ie. statistics, debuging, cleaning etc). All you need to do is create class instance and let PHP destroy it, however its hard to be sure whitch objest will “die” first.

  • http://www.mixedwaves.com Penuel

    Nice round-up!!

  • http://www.oryzone.com loige

    There were some things that I didn’t know before reading this interesting article: glob, compressing strings, and cpu usage :)
    So really thanks for sharing.

    I thinks that would be funny also speaking about var_dump, print_r, var_export and json_encode/decode ;)

    • http://www.oryzone.com loige

      Another great tip that i’ve learned by reading some parts of the source code of the yii framework (http://www.yiiframework.com/) is the ability to to use return statements with include o require statements.
      Generally when you call include o require and assign the result to a variable, that variable will get a boolean value that indicates whether the file has been included or not.
      But if the included file has a return statement the returned value will be returned also form the include function, so the variable will also get that value instead of the common boolean value.

      Here’s an example:


      “world”, “foo” => “bar”, “name” => “john doe”);
      ?>

      it will output:

      Array ( [hello] => world [foo] => bar [name] => john doe )

      As showed, it would be very useful when you need to create configuration files defined with php arrays, also symfony does somithing similar converting yaml and xml configurations files to php arrays before importing them qith a require or include statement…
      Also simple i18n system can be easily build using this technique.

      (sorry for my poor english :P)

      • http://www.oryzone.com loige

        Sorry parts og my code have been stripped… here’s the example again… i hope it works right now

        Here’s an example:

        [ config.php ]
        return array(“hello” => “world”, “foo” => “bar”, “name” => “john doe”);

        [ index.php ]
        $config = require(“config.php”);
        print_r($config);

        it will output:

        Array (
        [hello] => world
        [foo] => bar
        [name] => john doe
        )

  • sebastian green

    Thanks, great article.

    Don’t think you can ever know all the available functions in PHP.

    • http://www.phpandstuff.com/ Burak
      Author

      That is true. I come across new ones all the time while casually browsing the manual pages.

  • http://www.bionicworks.com Thai

    Some of the examples are so clear and straight to the point. These little details are really nice when the manual can be partial about certain methods. Thank you so much!

  • http://www.lukasfiala.com Lukas

    Great article :)

  • http://danieldeveloper.com Daniel

    Cool Job!!!

  • http://www.satya-weblog.com Satya Prakash
  • abdeslem Menacere

    Nice article. :)

    very useful.