How to work with closures

How to create a closure

An array of arrays

      $employees = array ( array('name' => 'Ray', 'id' => 5685), array('name' => 'Mike', 'id' => 4302), array('name' => 'Anne', 'id' => 3674), array('name' => 'Pren', 'id' => 1527), array('name' => 'Joel', 'id' => 6256) );
      

A function to sort the array by any column

      function array_compare_factory($sort_key) { 
        return function ($left, $right) use ($sort_key) { 
          if ($left[$sort_key] < $right[$sort_key]) {
            return -1; 
          } else if ($left[$sort_key] > $right[$sort_key]) { 
            return 1; 
          } else { 
            return 0; 
          } 
        };
      }
      

Code that sorts the array by the name column

      $sort_by_name = array_compare_factory('name'); 
      usort($employees, $sort_by_name);
      

Code that sorts the array by the id column

      $sort_by_id = array_compare_factory('id'); 
      usort($employees, $sort_by_id);
      

The comparison function with the spaceship operator (PHP 7 and later)

      function array_compare_factory($sort_key) { 
        return function ($left, $right) use ($sort_key) { 
          return $left[$sort_key] <=> $right[$sort_key]; 
        }; 
      }
      

Back