Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 29 / 68

Higher-Order Functions (Passing a Function as an Argument)

In this lesson you will learn the idea of higher-order functions in PHP so you can write flexible code that takes a function as an argument. This is for anyone searching for "PHP higher-order function usort how to use".

Passing another function as an argument is what makes something a higher-order function. Picture handing over the rules for a job and letting someone else do the work. Giving a comparison rule to usort() is the classic example.

The sample code passes an anonymous function carrying its own comparison rule to usort(), as in usort($nums, function ($a, $b) { return $b - $a; });, sorting in descending order. The array_map you met earlier is in fact another higher-order function.

A common stumbling block for beginners is what the comparison function's return value means. Returning a negative number means "a comes before b" and a positive number means "a comes after b"; without that, the order will not be what you expected.

Once you can define higher-order functions yourself, you can package shared logic as parts and make your code far more reusable. It is one of the key ideas behind modern PHP style.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)