Nice but what’s the point? Well recently I needed a native PHP implementation of the in built array_change_key_case() function, for PHP versions below 4.2.0 (which is when it became available). Thanks to the first user submitted comment from 05-Feb-2004, didn’t even need to engage my brain. Had this straight away;

[small]Note the use of the $return array is because the in built implementation of array_change_key_case() eliminates duplicate keys.[/small]

But there’s a performance issue here. For each element in the array, the switch condition has to evaluated. For a large array, that could become a significant overhead. What I want is to evaluate the condition once and only once.

By placing the function name I want to use (strtolower() or strtoupper()) in a variable, before I start looping through the array, the condition is only evaluated once. For a small array, the performance benefit is insignificant but when you’re handling alot of data you might start noticing the difference…

Lambda Functions
Now being able to place just a function name in a variable is nice but life get’s even more interesting when you look at create_function(), a PHP function for creating other functions!

In essence, it allows you to create a function and store it in a variable, without having to give the function a name.

The first line, if you declared it normally as a function, would look like this;

function "anonymous"(& $str) {
$str = strtolower($str);
}

Where this comes in handy is, again, when processing large sets of data.

Using a similar, hypothetical example to the one above, let’s say you need a function for calculating sales tax (VAT) from your online shop (nRonOnline.com). Let’s say VAT is set at 17% so this needs to be added to the price of items you are selling.

Being a sharky individual, you spot a chance for some extra profit with some dubious fiddling of numbers. For customers you’ll calculate tax and round up to the nearest whole number. But when it comes to reporting to the tax man, you’ll round down the figure that includes tax (don’t try this at home!).