How to work with anonymous functions

How to create and use an anonymous function

A custom sorting function

      $compare_function = function($left, $right) { 
        $l = (float) 
        $left; 
        $r = (float) $right; 
        if ($l < $r) { return -1;  }
        if ($l > $r) { return 1; }
        return 0; 
      }; 
      

Code that tests the custom sorting function

      $a = 3; 
      $b = 5; 
      $result = $compare_function($a, $b); // -1 
      

Code that uses the custom sorting function

       $values = array(5, 2, 4, 1, 3); 
       usort($values, $compare_function); // 1, 2, 3, 4, 5
      

A custom sorting function that takes advantage of PHP 7 features

       $compare_function = function(float $left, float $right) { 
         return $left <=> $right; // the "spaceship" operator
       };
      

Back