Last Updated: February 25, 2016
·
2.269K
· felipelavinz

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;
});

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside