Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP additional parameters to usort

Tags:

php

usort

The following code lays within a function which itself lays within a class. Its purpose is to avoid having one sorting function per $filter value :

$GLOBAL['filter'] = $filter;
usort($this->data, function($arr1, $arr2) {
    return ($arr1[$GLOBALS['filter']] > $arr2[$GLOBALS['filter']]) ? 1 : -1;
});

My solution works perfectly fine, but I find it rather inelegant. Would somebody have an idea to acheive the same goal without resorting to the $GLOBALS variable ?

Thanks for your propositions

like image 884
Lanz Avatar asked Sep 21 '11 06:09

Lanz


People also ask

Is PHP Usort stable?

Sorting functions in PHP are currently unstable, which means that the order of “equal” elements is not guaranteed.

What is usort() in PHP?

The usort() function in PHP sorts a given array by using a user-defined comparison function.

How to sort PHP object array?

The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field.

What is Uasort?

The uasort() function sorts an array by values using a user-defined comparison function. Tip: Use the uksort() function to sort an array by keys using a user-defined comparison function.


1 Answers

Since you're using an anonymous function, you can use it as a closure like this:

$filter = <whatever>;
usort($this->data, function($arr1, $arr2) use ($filter) {
    return ($arr1[$filter] > $arr2[$filter]) ? 1 : -1;
});
like image 134
Matteo Riva Avatar answered Oct 01 '22 23:10

Matteo Riva