Thinking Functionally In PHP

November 22, 2011

I’ve noticed a trend in PHP code to shy away from function application and closures. I understand to some extent. Useful, inline anonymous functions were not available until 5.3.0, which is relatively new. And create_function is an abomination.

Still, I think that PHP programmers just don’t think in this mindset, but it can be very useful.

Here is a rather contrived example, but one I’ve honestly seen an analogue of before.

Easy to understand, simple, does the job, but it is far more verbose than it needs to be.

Here is a version using array_map.

The array_map function is doing all the work of the loop, but you don’t have to write it and you don’t have to manage the accumulator.

Doesn’t that feel better?

Next time you mangle an array, first think if array_map or it’s friends array_filter or array_reduce could do it better.

Categories: Geek
Tags: , ,

Leave A Comment

Your email will not be published.