0

There are a few posts here on SO that concern with sorting multidimensional arrays in php and I can get it to work fine when using:

usort($list, function($a, $b)
            {
                return $a['content_id'] <=> $b['content_id'];
            }
        );

But I can't find any reference to using a variable to sort with. When I try to use one, I get an error. eg in this example:

    $sortVariable='content_id';
    usort($list, function($a, $b)
            {
                return $a[$sortVariable] <=> $b[$sortVariable];
            }
        );

It doesn't work and I am not sure why - I get the 'Undefined variable' error. Looking for help, thanks

0

1 Answer 1

1

That's due to variable scope. $sortVariable is not available inside of your function. To make it available to your closure use the use language construct:

$sortVariable='content_id';
usort($list, function($a, $b) use ($sortVariable) {
    return $a[$sortVariable] <=> $b[$sortVariable];
});
1
  • Thanks, I thought it was a scope issue, this is great May 24, 2020 at 11:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.