Injecting variables into anonymous functions in PHP

I was coding up some tools yesterday, and decided to write a function in PHP that sorted an array numerically by a provided subkey name.

Assume an array with the following structure:

1
2
3
4
5
6
7
8
9
10
$sale_items = array(
   "first" => array(
      "value" => "100",
      "color" => "blue"
   ),
   "second" => array(
      "value" => "105",
      "color" => "red"
   )
);

uasort can easily handle this if you already know which subkey you intend to sort by:

1
2
3
$sorted = uasort($sale_items, function($a, $b) {
   return ($a['value'] > $b['value']);
});

In this case though, I wanted to make this function reusable. Unfortunately the uasort function passes the parameters the provided function on its own – how do we inject a variable into that anonymous function? Turns out that it’s insanely easy. Check it:

1
2
3
$sorted = uasort($sale_items, function($a, $b) use ($field) {
   return ($a[$field] > $b[$field]);
});

Done.

Leave a Reply

Your email address will not be published. Required fields are marked *