web-profile

php anonymous functions

Anonymous functions are available from PHP 5.3 (2009).

Anonymous functions are useful when using functions that require a callback function like array_filter or array_map do:

$arr = range(0, 10);
$arr_even = array_filter($arr, function($val) { return $val % 2 == 0; });
$arr_square = array_map(function($val) { return $val * $val; }, $arr);
// The function doesn't need to be assigned to a variable. This is valid too:
$arr_even = array_filter($arr, function($val) {
    return $val % 2 == 0;
});

Otherwise you would need to define a function that you possibly only use once:

function isEven($val) { return $val % 2 == 0; }
$arr_even = array_filter($arr, 'isEven');
function square($val) { return $val * $val; }
$arr_square = array_map('square', $arr);

The lambda function is an anonymous PHP function that can be stored in a variable and passed as an argument to other functions or methods. A closure is a lambda function that is aware of its surrounding context.

The lambda functions and closures are often used with the array_map(), array_reduce(), and array_filter() functions:

$input = array(1, 2, 3, 4, 5);
$output = array_filter($input, function ($v) { return $v > 2; });

The above example filters the input array by removing all values greater than 2:

$output == array(2 => 3, 3 => 4, 4 => 5)

function ($v) { return $v > 2; } is the lambda function definition and it can be stored in a PHP variable to be reusable:

$max_comparator = function ($v) { return $v > 2; };
$input = array(1, 2, 3, 4, 5);
$output = array_filter($input, $max_comparator);

But what if I want to change the maximum number allowed in the filtered array? I can either create another lambda function or use a closure:

$max_comparator = function ($max) {
  return function ($v) use ($max) { return $v > $max; };
};
$input = array(1, 2, 3, 4, 5);
$output = array_filter($input, $max_comparator(2));

Now, the $max_comparator function takes the maximum allowed number and returns a function that is different according to this maximum.

Leave a Reply

Your email address will not be published. Required fields are marked *