craig campbell

Anonymous PHP Functions

created July 24, 2010 at 2:22 pm
Most PHP developers are probably well aware of this already, but the release of PHP 5.3 brought a few cool features to the language including namespaces, late static binding, and anonymous functions (closures).

In the interest of keeping this brief I just wanted to provide a few simple examples.

Let's imagine you have an array of data:
$users = array( array('id' => 1, 'name' => 'Tom', 'birthdate' => '1980-05-05'), array('id' => 2, 'name' => 'Julia', 'birthdate' => '1985-07-07'), array('id' => 3, 'name' => 'Michael', 'birthdate' => '1974-11-17') );
Now let's say you wanted to grab all the user ids from this array. Normally you would do something like this:
$ids = array(); foreach ($users as $user) { $ids[] = $user['id']; }
With anonymous functions you could achieve the same thing by doing:
$ids = array_map(function ($user) { return $user['id']; }, $users);

Now let's say you wanted to filter out all the users born after 1980. The traditional way would look something like this:
$filtered_users = array(); $start_date = strtotime('1979-12-31'); foreach ($users as $user) { if (strtotime($user['birthdate']) > $start_date) { $filtered_users[] = $user; } }
With anonymous functions:
$start_date = strtotime('1979-12-31'); $filtered_users = array_filter($users, function($user) { global $start_date; return strtotime($user['birthdate']) > $start_date; });

I'm not suggesting that you necessarily SHOULD do this. The foreach loops are arguably more readable, and in simple benchmarks, they outperform using array functions 90% of the time. However, it is something else to add to your bag of tricks and can be useful in places where you need a one off callback function.

0 comments