Articles / Tips and Tricks

Using anonymous functions and closures for user-defined array sorting

Anonymous functions and closures are relatively new in PHP, but they’re extremely welcome.

Whenever you need to sort an array with a custom order (that is, with a user-defined comparison function such as usort, uasort or uksort) you can use anonymous functions and closures in an easy and very straight-forward way.

For instance:

// assuming you have your un-sorted elements on $elements
// and the customized order on $order

usort( $elements, function($a, $b) use ($order){
    $a_index = array_search($a->ID, $order);
    $b_index = array_search($b->ID, $order);
    if ( $a_index > $b_index ) return 1;
    if ( $a_index > $b_index ) return -1;
    return 0;
});