Home
«  Previous Next  »

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()


<!DOCTYPE html>
 <html>
   <body>
   <?php 
    $array = array(
			"This seems to be  long string,
	    		one Word", "THIS", "CALL",
			"spidder man could", "can be bigger"
			);
  usort($array, function($str) {
	if ( ctype_upper($str)){
		return -1;
	}elseif ( !ctype_upper($str)){
		return 1;
	}else {
		return 0;
	}
 });
print_r($array);   
     ?>      
      Output: -
Array ( [0] => THIS [1] => CALL 
        [2] => This seems to be long string,one Word
        [3] => spidder man could
        [4] => can be bigger
      )   
    </body>
 </html>
    

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.

Example ⇓shows an example using usort()


<!DOCTYPE html>
 <html>
   <body>
   <?php 
    $array = array(
			"This seems to be  long string,
	    		one Word", "THIS", "CALL",
			"spidder man could", "can be bigger"
			);
  usort($array, function($a, $b) {

	   return strlen($a) - strlen($b);
	
 });
print_r($array);   
     ?>      
      Output: -
Array ( [0] => THIS [1] => call
        [2] => can be bigger
        [3] => spidder man could 
        [4] => This seems to be long string, one Word
      )     
    </body>
 </html>
    
«  Previous Next  »
Advertise Here ...