Q. Explain lambda function in php with examples.
Answer:
In PHP, a lambda function is a concise way to create anonymous functions, also known as closures. Anonymous functions are functions without a specified name. Lambda functions are useful in situations where a small, unnamed function is needed for a short period, such as passing a function as an argument to another function or using it in a callback.
Here's the basic syntax for a lambda function in PHP:
$lambdaFunction = function ($param1, $param2, ...) {
// Function body
return $result;
};
Here's an example to illustrate the use of lambda functions:
// Example 1: Simple lambda function
$addition = function ($a, $b) {
return $a + $b;
};
$result = $addition(3, 4); // Result is 7
echo $result;
// Example 2: Using lambda function as an argument
$numbers = [1, 2, 3, 4, 5];
// Using array_map with a lambda function to square each number
$squaredNumbers = array_map(function ($number) {
return $number * $number;
}, $numbers);
print_r($squaredNumbers); // Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
In Example 1, a lambda function is assigned to the variable $addition, and it adds two numbers. The lambda function is then called with arguments 3 and 4, resulting in 7.
In Example 2, a lambda function is used as an argument to array_map. This function applies the lambda function (which squares each number) to each element of the $numbers array, resulting in an array of squared numbers.
Lambda functions are often used in functions like array_map, array_filter, and as callbacks in functions like usort. They provide a concise way to define simple functionality without the need to declare a separate named function.
No comments:
Post a Comment