jmhobbs

Thinking Functionally In PHP

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.

$accumulator = array();
foreach( $this->tags->all() as $tags ) {
  $accumulator[] = htmlspecialchars( $tag->name );
}
return implode( ', ',  $accumulator );

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.

$tags = array_map( 'htmlspecialchars', $this->tags->all() );
return implode( ', ', $tags );

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.