For and by top PHP developers

Using powerful PHP array functions

There is a wealth of useful power in the PHP array functions. They are generally much more efficient than writing your own PHP code, since they are compiled. Not that I'm against PHP being an interpreted language, there are a lot of advantages in that. But you should still take advantage of efficiency where it is easily available.

Today, I stumbled across a relatively simple function in Joomla. Some of my development work is of add-ons that can be run in Joomla, so I find myself poking around it from time to time. The routine is supposed to force the elements of an array into being integers, and it goes like this:

The first thing that is wrong with it is that it is a static method, and in PHP5 it would be declared as public static function. But the argument over static methods is for another day! So the next thing to look at is the operation to force the array elements to be integers.

Well, if you want to do something to every element of an array, PHP has got the answer already in the form of the array_map function. We can get the same effect more efficiently and more succinctly by saying $array = array_map('intval', $array);

The next thing to notice is all the messing around with the default. We can get rid of it just by coercing the default into an array. The ability to coerce things into an array is another very powerful feature of PHP array processing. And PHP neatly matches up with our requirement by coercing null into an array without any elements. So, bringing in the logic that tells us whether to use the default or not, we can rewrite the method as:

At this point we might wonder whether it was worth making it a method at all! Although perhaps that still saves us the time of thinking up a moderately complex statement if we are really going to make use of the default. For those times when the default is not needed, it's hardly worth calling a class method. We might as well write the shorter and much more efficient: