Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top