PHP is a fairly large language, with many functions available to developers, including a few that you probably didn’t know existed. This post is going to take a brief look at various functions in the PHP programming language that are often overlooked, forgotten, or just unknown. Let’s just jump right in, shall we?
Have you ever wanted to see every variable defined in your PHP script. $_GET, $_POST, $_GLOBALS, $_SERVER, user defined. When called every, single, variable, that is defined is returned as an array.
Has your server been sluggish lately and you can’t figure out why? This function would come in handy, especially if you are working on a shared hosting environment and you don’t have full access to the server’s logs. sys_getloadavg() returns an array with the average system load over the last 1, 5, and 15 minutes. On my local machine these were my results:
As you can see, my machine is really showing offthe computational muscle (well, not really).
Ever find the need to determine how different (or similar) two words are? Then levenshtein() is just the function you need. The PHP manual suggests using levenshtein() to determine if a user submitted a typo.
Allow me to set the scene. It’s a beautiful summer afternoon on a Friday, the clock is ticking away. Every time you look up you see it is later and later, first it’s 4:30pm. Then 6:00pm. Now it’s 8:00pm and it is now well beyond time to go home for the weekend, but there is one bug in your application that you just can’t squash. You keep submitting your HTML form over and over but the data isn’t being processed correctly. You waste time after each modification to the code filling in the same information, over and over, but the output still isn’t what you expect. Here is where parse_str() will come into handy. Simply supply a string of arguments that you wish to be mapped to your $_POST variable and away you go.
$str = "firstName=Test&lastName=Data&address=123+Main+Street&address=A+City,+A+State+12345";
string(15) "123 Main Street"
string(21) "A City, A State 12345"
Unfortunately this gem was removed in PHP 5.5. But, did you know that you could output a modified version of the PHP logo with the ElePHPant with a simple function call?
echo '<img src="'.$_SERVER['PHP_SELF'].'?='.php_egg_logo_guid().'"/>';
If you want to see the output, go ahead and give it a run on your server.
These are a few of a lesser known functions in the PHP language. There are many more buried under the hood. A bit of digging through the manual will uncover plenty of other useful (or in the case of php_egg_logo_guid(), fun) functions that were just waiting to be discovered. What are some of your favorite lesser known functions?