PHP Anonymous Functions

Anonymous Functions have no given function name unlike normal functions, this is also known as closures. You will mostly use Anonymous Functions in other php functions as parameters, (callback parameters)

Some PHP functions use a function as parameter or as callback function to do part of their work.

Let us see show cases here

the usort() function sorts an array by values using a user-defined comparison function.
Forexample, the usort() function takes two parameters , the array to be sorted and a callable $value_compare_func respectively. This second paramter (the user defined comparison function) gives you the possibilitiy to tell the usort function your condition of sorting and that is where Anonymous Functions are fit to be used, these functions tend to be localized and temporary.
In the following Example we are going to sort the element of the array by using the usort but with the condition, so that elements which are capitalized comes first. Syntax of Anonymous functions
You can create an anonymous function using the normal function definition syntax, but assign it to a variable or pass it directly.

Note that PHP supports this feature beginning from the version php 5.3

Example ⇓shows an example using usort()


The following Example show the usage of anonymous functions with usort function but with different sorting condition.
Elements of the array will be sorted according to their length. Shorter ones comes first


You can get the E-mails belong to specific provider using anonymous function

Fore example, if you have a list of E-mails or a large array of Emails and you want get the ones belonging to a specific provider, for instance google. You can walk through the array , use anonymous function and locate the sub-string of the ‘gmail’ .


Email Owner => Al | E-mails of provider => Email Owner => bt | E-mails of provider => Email Owner => ykt | E-mails of provider =>