Anonymous Function in PHP

In Lisp or Scheme language, the anonymous function (which is called lambda-style function) is common used. These functions are special because it doesn’t have a name. So it can be only used once. Usually, these functions are very small and simple.

What these strange functions can be used for? Suppose there is an array that contains some integers. For example, $a=array(34,21,58,32,19,6). And we want to use “array_filter” function to retrieve the odd integers. The usage of the array_filter is:
array array_filter(array $input [,callback $callback])
The function iterates each element in $input. The $callback is a function which returns true or false. If it returns true, the current element is pushed into the result array. Using array_filter, it is easy to write the following code:

<?php
function is_odd($n){
	if ($n%2==1)
		return true;
	else
		return false;
}
$a=array(34,21,58,32,19,6);
$result=array_filter($a,'is_odd');
print_r($result);
?>

Its output is:

Array
(
    [1] => 21
    [4] => 19
)

Obviously, there is a small function “is_odd” to check if an integer is an odd number or not. However, it is used only in array_filter function. So if we can define the small function in array_filter’s second argument’s place, it is a better style.

PHP provides “create_function” that can create an anonymous function. The usage:
string create_function(string $args, string $code)
Now use this function to rewrite the example:

<?php
$a=array(34,21,58,32,19,6);
$result=array_filter($a,create_function('$n','return ($n%2==1)?true:false;'));
print_r($result);
?>

Tags: ,

4 Responses to “Anonymous Function in PHP”

  1. Thomas says:

    This doesn’t really make an anonymous function, it makes a function with a randomized name, returning it as a string. It’ll create a new function every time it’s called, and basically has the same sort of overhead as eval().

    PHP 5.3 does include proper anonymous functions (see http://wiki.php.net/rfc/closures), so you can write:

    array_filter($a, function($n){ return($n % 2 == 0); })

    Also, your ?true:false is utterly superfluous; == already returns a boolean.

  2. Binny V A says:

    Thanks for the post. I’m waiting for my admins to install PHP 5.3 on my servers so that I can use the code Thomas described. That’s a much more elegant solution than the current method. Also, it reminds me of javascript.

  3. This is not anonymous functions, way to have no clue what you’re talking about.

  4. alex says:

    so is creating a create_function function creating more overhead then a normal function, say if it’s in a loop?

Leave a Reply