Tuesday 30 August 2011

PHP Anonymous Functions

I had to write a simple function in PHP to generate an id of the format dd-dd-dd-dd-dd-dd (where d is a digit). I thought I'd use it to try PHP's Anonymous functions with more of a functional programming approach, this is what I came up with:

$id = implode('-', array_map(function($n) { return sprintf('%02d', mt_rand(0, 99)); }, array_fill(0, 6, 0)));

It works fine and can be put all on one line (although a 109 char line) but realistically should be split for readability as I find it quite incomprehensible. Maybe:

$id = implode('-', array_map(
    function($n) { return sprintf('%02d', mt_rand(0, 99)); },
    array_fill(0, 6, 0)
));

Whilst that was interesting, in the end I used a more conventional approach (for readability and maintainability):

$numbers = array();
while (count($numbers) < 6) {
    $numbers[] = sprintf('%02d', mt_rand(0, 99));
}
$id = implode('-', $numbers);