Home
Map
function, Lambda Expression ExamplesUse function syntax with lambda expressions and the fn keyword to specify logic to another function.
PHP
This page was last reviewed on Jun 3, 2023.
Function. In PHP we call functions throughout our programs. We have 3 important syntax forms for functions, all of which can handle arguments and return values.
With the fn keyword, we use lambda expressions—these have simpler bodies and cannot include multiple statements. Anonymous functions can have more complex logic.
Example. We declare an array of 4 integers and then filter it with array_filter. We want to remove elements that are less than 3, so the result has just 3 and 4.
array
Version 1 We use the "fn" keyword with a fat arrow to filter the array. The argument is named "x".
Version 2 We use an anonymous function, which uses the "function" keyword and then a block of code surrounded in curly braces.
Version 3 We use a named function, which must be specified as a string literal. This calls the filter_test function.
function filter_test($x) { // Used in an array_filter call. return $x >= 3; } $values = [1, 2, 3, 4]; // Version 1: use fn with fat arrow to filter array. $result = array_filter($values, fn ($x) => $x >= 3); var_dump($result); // Version 2: use anonymous function to filter array. $result = array_filter($values, function($x) { return $x >= 3; }); var_dump($result); // Version 3: use named function. $result = array_filter($values, "filter_test"); var_dump($result);
array(2) { [2]=> int(3) [3]=> int(4) } array(2) { [2]=> int(3) [3]=> int(4) } array(2) { [2]=> int(3) [3]=> int(4) }
Multiple return values. It is possible to return multiple values from a function in PHP. We use the short array syntax and return the values in an array.
function get_name_and_weight($id) { // Return multiple values from function. if ($id == 0) { return ["", 0]; } else { return ["X250", 100]; } } // Get the array result. $result = get_name_and_weight(0); var_dump($result); $result = get_name_and_weight(1); var_dump($result);
array(2) { [0]=> string(0) "" [1]=> int(0) } array(2) { [0]=> string(4) "X250" [1]=> int(100) }
With function syntax we specify logical behavior and can pass functions as arguments to other functions. These are higher-order functions, and they provide a powerful feature to PHP.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 3, 2023 (new example).
Home
Changes
© 2007-2024 Sam Allen.