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.
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.
fn
" keyword with a fat arrow to filter the array. The argument is named "x".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) }
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.