PHPBuilder - Lambdas in PHP



RSS Twitter
Articles Php Functions

Lambdas in PHP

by: PHP Builder Staff
|
April 16, 2014

Introduction

This article is intended to be a guide to lambda functions in PHP. We will learn more about lambda expressions and lambda PHP functions and then we are going step by step through different kinds of examples--from basic lambda functions, recursive lambda functions, lambda functions in PHP arrays and in PHP classes.

 

What are Lambdas in PHP and why Should we use them?

A lambda is an anonymous function, a function defined with no name that can be stored in a variable and that can be passed as an argument to other functions or methods. In other words, lambda functions are simply throwaway functions that can be defined at any time and are normally attached to a variable. The lambda functions only exist as long as the variables of which they are defined exist, so when that variable goes out of scope, so does the function.

 

Lambda functions are useful for a number of instances, most notably for many PHP functions that accept a callback function. One such function is array_map(), which allows us to walk through an array and apply a callback function to each element of the array.

 

Lambdas Expressions

Lambdas expressions are practically the fundamental concept within computer science and mathematics. The lambda calculus consists of a language of lambda terms, which is defined by a certain formal syntax, and a set of transformation rules, which allow manipulation of the lambda terms. The syntax of the lambda calculus defines some expressions as valid lambda calculus expression. An example of lambda expression is factorial F(n), which is also part of this article as a PHP script that uses lambda function, in a below section:

 

F(n) = 1, if n = 0; else n × F(n − 1) - the computable factorial function

 

Y := λg.(λx.g (x x)) (λx.g (x x)) - lambda expression of factorial

 

Basic PHP Lambda Functions

In PHP, lambda functions were introduced from the PHP 4.0.1 version, through the create_function() method, but starting with the PHP 5.3+ version, the lambda function syntax became similar with JavaScipt, so now is a much more readable and convenient way to define a function. The syntax of a lambda function is:

 

function & (arguments) use (variables) { code }

 

So, the first PHP application that uses the lambda functions, from this article is a "Hello World example"

 

<?php

$lambda = function() {
return 'Hello, World!';
};
echo $lambda();
?>

 

The output is:

 

Hello, World! 

 

You can now see a simple JavaScript lambda function that calculates sum of two numbers and right after it is the PHP lambda function which does the same thing, as I said in the first part of this section they are very similar:

 

var sum = function(a, b) { return a + b; }

alert(sum(15, 2)); 

 

Notice that, in the PHP example, the semicolon is mandatory after defining the lambda function:

 

<?php

$lambda = function($a, $b) {
return $a + $b;
};
echo 'Sum='.$lambda(5,2);
?> 

 

The output is:

 

Sum=7

 

Next is also a simple example of lambda function that outputs square(15):

 

<?php
$square = function($x) {
return $x * $x;
};
echo 'Result='.$square(15);
?> 

 

The output is:

 

Result=225

 

Recursive Lambda Functions in PHP

In this section we will create recursive lambda functions as factorial, a sum of a given number of consecutive terms and the Fibonacci function. For creating recursive lambda function we will use Y-combinator. In computer science, a fixed-point combinator is a higher-order function y that satisfies the equation. A combinator is a particular type of higher-order function that may be used in defining functions without using variables. The combinators may be combined to direct values to their correct places in the expression without ever naming them as variables." You can learn and understand more about Y-combinator < href="http://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator" target="new">here.

 

First application returns a factorial number:

 

<?php
$factorial = function( $n ) use ( &$factorial ) {
if( $n == 1 ) return 1;
return $factorial( $n - 1 ) * $n;
};
print 'Factorial='.$factorial( 8 );
?> 

 

The output is:

 

Factorial = 40320

 

Next application calculates the first n consecutives number sum, in our case 1+2+3+…+23:

 

<?php

$recursive_sum = function( $n ) use ( &$recursive_sum ) {
if( $n == 0 ) {$var = 0; return 0;}
return $recursive_sum( $n - 1 ) + $n;
};
print 'The recursive sum: 1+2+3+…+23 = '.$recursive_sum(23);

?> 

 

The output is:

 

The recursive sum: 1+2+3+…+23 = 276

 

And the last application from this section is the Fibonacci:

 

<?php
$fibonacci = function($n)use(&$fibonacci)
{
if($n == 0 || $n == 1) return 1;
return $fibonacci($n - 1) + $fibonacci($n - 2);
};

print 'Fibonacci result is = '.$fibonacci(9);
?> 

 

The output is:

 

Fibonacci result is = 55

 

Lambda Functions in PHP Arrays

As we already said, the lambda functions allow the creation of functions that have no specified name. They are most useful as the value of callbacks parameters, as we will see in this section of this article, but they also have many other purposes. The lambda functions main goal is closely related with the array_map(), array_reduce(), array_filter(), array_walk() and usort() native PHP functions, listed and described below:

 

  • • array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()

 

array array_map (callable$callback , array $array1 [, array $... ] )

 

  • array_reduce() applies iteratively the callback function to the elements of the array, so as to reduce the array to a single value. If the optional initial is available, it will be used at the beginning of the process, or as a final result in case the array is empty.

 

mixed array_reduce ( array $array , callable $callback [,mixed$initial = NULL ] )

 

  • array_filter() iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

 

array array_filter ( array $array [,callable$callback ] )

 

  • array_walk() applies the user-defined callback function to each element of the array array.

 

bool array_walk ( array &$array , callable $callback [,mixed$userdata = NULL ] )

 

  • usort() -- Sort an array by values using a user-defined comparison function

 

bool usort ( array &$array , callable$value_compare_func )

 

<?php

$array = array(21, 52, 63, 94, 125, 49, 351, 876, 12, 3, 56);
echo 'Initial array : ';
foreach ($array as $i => $value) {
echo $array[$i].' ; ';
}
echo '<br>';

echo 'Listing elements of the array > 21 using array_filter(): ';
$output1 = array_filter($array, function ($v) { return $v > 21; });
foreach ($output1 as $i => $value) {
echo $output1[$i].' ; ';
}
echo '<br>';

echo 'Sorting descending the elements from the array using usort(): ';
usort($array, function ($a, $b) {
return $a < $b;
});
foreach ($array as $i => $value) {
echo $array[$i].' ; ';
}
echo '<br>';

echo 'Listing elements of the array *10 using array_map(): ';
$output2 = array_map(function($value) { return $value * 10; }, $array);
foreach ($output2 as $i => $value) {
echo $output2[$i].' ; ';
}
echo '<br>';

echo 'Listing the sum of elements from the array using array_reduce(): ';
print_r( array_reduce($array, function ($v1,$v2) { return $v1+$v2 ; }));


echo '<br>';
echo 'Listing the elements from the array*2 using array_walk(): ';
array_walk($array, function(&$value, $i){
if ($value > 0) $value *= 2;
});
foreach ($array as $i => $value) {
echo $array[$i].' ; ';
}
echo '<br>';


?> 

 

The output is:

 

Initial array : 21 ; 52 ; 63 ; 94 ; 125 ; 49 ; 351 ; 876 ; 12 ; 3 ; 56 ; 
Listing elements of the array > 21 using array_filter(): 52 ; 63 ; 94 ; 125 ; 49 ; 351 ; 876 ; 56 ; 
Sorting descending the elements from the array using usort(): 876 ; 351 ; 125 ; 94 ; 63 ; 56 ; 52 ; 49 ; 21 ; 12 ; 3 ; 
Listing elements of the array *10 using array_map(): 8760 ; 3510 ; 1250 ; 940 ; 630 ; 560 ; 520 ; 490 ; 210 ; 120 ; 30 ; 
Listing the sum of elements from the array using array_reduce(): 1702
Listing the elements from the array*2 using array_walk(): 1752 ; 702 ; 250 ; 188 ; 126 ; 112 ; 104 ; 98 ; 42 ; 24 ; 6 ;  

 

Lambda Function in PHP Classes

As you already learned by now, lambda is a function defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects, as you can see in the below examples.

 

This is a simple "Hello World" example of lambda object:

 

<?php
class Test {
public $A;
}

$B = new Test();
$B->A = function(){echo('Hello World!');};

call_user_func($B->A);
?>  

 

Outputs: Hello World!

 

PHP 5.3 and greater allows calling an object as a lambda function through the magic __invoke() method. The __invoke()method is called when a script tries to call an object as a function.

 

Below you can see a simple example that shows this:

 

<?php

class Test {
function __invoke($example) {
echo $example;
}
}

$example = new Test();
$example('This is a simple example of lambda function!');
?> 

 

Outputs: This is a simple example of lambda function!

 

Summary

This article has explored lambda expressions and lambda PHP functions and you have seen them at work in different PHP examples from basic lambda functions, recursive lambda functions, lambda functions in PHP arrays and PHP classes.

 

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:

Comment:



Comment:

(Maximum characters: 1200). You have characters left.