1

I am using php function usort to sort an array. The custom php function must be generated because its dynamic

$intCompareField = 2;
$functSort = function($a, $b) {
  return ($a[$intCompareField] > $a[$intCompareField])?1:-1;
}

usort($arrayToSort, $functSort);

The $intCompareField in the compare function is null, my guessing is because the $intCompareField was declared outside of the function. Setting global $intCompareField does not seem to work.

Ps: I am using $intCompareField because the array to sort is multidimensional and i want to be able what key in the array to sort.

3
  • Are you sure you want to only ever return 1 or -1, it is generally desired to return 0 for "equal" values. Commented Jan 25, 2012 at 9:12
  • I know that but i want to keep the function short. Thanks tough for the comment Commented Jan 27, 2012 at 10:21
  • So, you prefer short and broken over short —though not as short as before— and working? Good luck with that! Commented Jan 27, 2012 at 13:25

2 Answers 2

4

While Dor Shemer's answer would suffice, I find it often better to have a function which generates the required comparison function.

$functSort = function ($field) {
    return function($a, $b) use ($field) {
        // Do your comparison here
    };
};

$intCompareField = 2;
usort($arrayToSort, $functSort($intCompareField));

You could make the function in $functSort be a named function (e.g. sort_by_field_factory() or some other appropriate name), there's no requirement for it to be an anonymous function.

Sign up to request clarification or add additional context in comments.

Comments

3

Try adding use, which passes variables from the outer scope to anonymous functions

function($a, $b) use ($intCompareField) {
     return ($a[$intCompareField] > $a[$intCompareField])?1:-1;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.