Connect with us

10 PHP functions you (probably) never use

coding

10 PHP functions you (probably) never use

10 PHP functions you (probably) never use

When scripting in PHP, we often restrict ourselves to a limited number of API functions: the common ones, like print(), header(), define(), isset(), htmlspecialchars(), etc. If some needed functionality doesn’t exist, we often write it making use of these basic components which we have in mind. The PHP API actually offers a lot of functionality, some useless and some useful; often seldom used. I have been looking through the available functions and was interested to find some really cool functions that I should have known about. Here, I share my findings.

1. sys_getloadavg()

sys_getloadvg() is a function which returns three samples of the “load” on a system. Load is the number of processes in the system run queue. The 3 items in the array are the average load for the past 1, 5 and 15 minutes. The PHP Manual shows a great usage of this:

$load = sys_getloadavg();
if ($load[0] > 80) {
    header('HTTP/1.1 503 Too busy, try again later');
    die('Server too busy. Please try again later.');
}

Rather than have your web service become unavailable for everyone, you simply die when there’s too much load — primitively, this will allow some requests and deny others. The function will not work on Windows, though.

2. pack()

I actually use pack() fairly often, to make the 32-byte hexadecimal strings returned by md5() into 16-byte binary strings*:

$pass_hash = pack("H*", md5("my-password"));
$pass_hash = md5("my-password", true); // equivalent (PHP 5+)

It is very useful when storing data in databases; to save space. (In the case of packing hexadecimal values to binary strings).

3. cal_days_in_month()

cal_days_in_month() usefully returns the number of days in a given month:

$days = cal_days_in_month(CAL_GREGORIAN, date("m"), date("Y")); // 31
echo ( $days - date("d") + 1 ) . " days until " . date("F", mktime(0, 0, 0, date("m") + 1, 1, 1970));

4. _()

If you’ve developed for WordPress, you’ll know about the __() and _e() functions to make the software i18n-able. You can use gettext() (or _(), which is an alias), together with some other functions, to achieve the same functionality, in WordPress or not. This example was taken from the PHP Manual:

// Set language to German
setlocale(LC_ALL, 'de_DE');
 
// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");
 
// Choose domain
textdomain("myPHPApp");
 
echo _("Have a nice day");

You will need to build PHP with GNU gettext support. I suspect that there is a third-party solution out there which does the same thing, working on a standard installation. (Edit: in fact, there is — here;).

5. get_browser()

Wouldn’t it be nice to find out what a user’s browser could do before sending the page? Well, you can with get_browser(). You will need php_browscap.ini first, and point the browscap directive to the file. You could have something similar to this:

$browser = get_browser(null, true);
if(!$browser["frames"] || !$browser["cookies"])
  echo "Please download an up-to-date browser. Some sections of this site may be inaccessible";

This will not detect individual configurations of browsers, however; it can not be used to detect whether Javascript is enabled, for example. It may be useful to profile users — ie, by what browser and platform they use.

6. debug_print_backtrace()

It can be quite difficult to trace through code manually, particularly when looking for a logic error; after all, you wrote the logic! debug_print_backtrace() can get you out of a difficult situation. Here the function is being used to understand a rather pointless script:

$a = 0;
 
function iterate() {
	global $a;
	if( $a < 10 )
		recur();
	echo $a . ", ";
}
 
function recur() {
	global $a;
	$a++;
 
	// how did I get here?
	echo "\n\n\n";
	debug_print_backtrace();
 
	if( $a < 10 )
		iterate();
 
}
 
iterate();
 
# OUTPUT:

#0  recur() called at [C:\htdocs\php_stuff\index.php:8]
#1  iterate() called at [C:\htdocs\php_stuff\index.php:25]

#0  recur() called at [C:\htdocs\php_stuff\index.php:8]
#1  iterate() called at [C:\htdocs\php_stuff\index.php:21]
#2  recur() called at [C:\htdocs\php_stuff\index.php:8]
#3  iterate() called at [C:\htdocs\php_stuff\index.php:25]

#0  recur() called at [C:\htdocs\php_stuff\index.php:8]
#1  iterate() called at [C:\htdocs\php_stuff\index.php:21]
#2  recur() called at [C:\htdocs\php_stuff\index.php:8]
#3  iterate() called at [C:\htdocs\php_stuff\index.php:21]
#4  recur() called at [C:\htdocs\php_stuff\index.php:8]
#5  iterate() called at [C:\htdocs\php_stuff\index.php:25]

[...]

7. metaphone()

metaphone() is a function returning the same key for words which sound the same. soundex() does the same thing, but is less accurate (according to PHP Manual):

echo metaphone("train") . "\n"; // TRN
echo metaphone("terrain") . "\n"; // TRN
echo metaphone("not a train") . "\n"; // NTTRN
 
echo soundex("train") . "\n"; // T650
echo soundex("terrain") . "\n"; // T650
echo soundex("not a train"); // N336

8. natsort()

natsort() is a function which will sort items in an array naturally (ie, in an order which seems logical to a person), rather than by characters’ ordinal values. Take, for example:

$items = array(
	"100 apples", "5 apples", "110 apples", "55 apples"
	);
 
// normal sorting:
sort($items);
print_r($items);
# Outputs:
# Array
# (
#     [0] => 100 apples
#     [1] => 110 apples
#     [2] => 5 apples
#     [3] => 55 apples
# )

natsort($items);
print_r($items);
# Outputs:
# Array
# (
#     [2] => 5 apples
#     [3] => 55 apples
#     [0] => 100 apples
#     [1] => 110 apples
# )

9. levenshtein()

levenshtein() tells you how “far” away two words are. It will return the minimum number of inserts, replaces and deletions needed to transform one string to the other. Take, for example, the following code:

$dictionary = array(
		"php", "javascript", "css"
	);
 
$word = "japhp";
 
$best_match = $dictionary[0];
$match_value = levenshtein($dictionary[0], $word);
 
foreach($dictionary as $w) {
	$value = levenshtein($word, $w);
	if( $value < $match_value ) {
		$best_match = $w;
		$match_value = $value;
	}
}
 
echo "Did you mean the '$best_match' category?";

In this case, the user has been asked to provide a category name. They provided “japhp”, which is invalid. Since this is likely to be a typing error, the code above will make a suggestion (“Did you mean the ‘php’ category?”).

10. glob()

glob() will make you feel stupid after using opendir(), readdir() and closedir() to search for a file. It’s this simple:

foreach (glob("*.php") as $file)
    echo "$file\n";

Any more?

There are loads of functions out there. If you can’t get enough, http_build_query()register_shutdown_function() and pspell_suggest are also worth a mention.What’s your favourite discovery?

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

More in coding

To Top