0

I have a sort function with a multidimensional array, but it doesn't work when I use a variable.

This works

function orderdata($l_col, $l_dir, $l_data) {

    usort($l_data, function ($a, $b) {
        return $a[0] <=> $b[0];
    });
    return $l_data;
}

This does not work ($l_col is 0)

function orderdata($l_col, $l_dir, $l_data) {

    usort($l_data, function ($a, $b) {
        return $a[$l_col] <=> $b[$l_col];
    });
    return $l_data;
}

What is the proper syntax?

Nesku
  • 501
  • 1
  • 6
  • 12
B. Swans
  • 13
  • 2
  • `$l_col` isn't in scope in the closure, you need to `use()` it. See *Extending the scope of variables into anonymous functions* in the suggested duplicate. – iainn Nov 21 '18 at 13:33

2 Answers2

1

You'll have to import $l_col into the closure with the use language construct.

The manual states:

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. From PHP 7.1, these variables must not include superglobals, $this, or variables with the same name as a parameter.

function orderdata($l_col,$l_dir,$l_data) {
    usort($l_data, function($a, $b) use ($l_col) { 
        return $a[$l_col] <=> $b[$l_col]; 
    }); 
    return $l_data;
}
DigiLive
  • 1,093
  • 1
  • 11
  • 28
0

Try the following:

function orderdata($l_col,$l_dir,$l_data) {
    usort($l_data, function($a, $b) use $l_col{
      return $a[$l_col] <=> $b[$l_col];
    });
    return $l_data;
}

Note that $l_col was inaccessible in your anonymous sorting function and you have to pass it explicitly to add it to the scope.

Blackbam
  • 17,496
  • 26
  • 97
  • 150
Manoj Singh
  • 253
  • 1
  • 7
  • Great, thanks for the responses Nigel and Manoj! The use command was new to me, so i appreciate it. – B. Swans Nov 21 '18 at 13:37
  • 1
    This answer looks correct but it is not (it doesn't compile). Next time check the correctness of the answer and explain why your answer solves the OP's question. Read more about [inheriting variables from the enclosing scope](http://php.net/manual/en/functions.anonymous.php) in anonymous functions. – axiac Nov 21 '18 at 13:40