Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: how to use usort with anonymous function?

Tags:

arrays

php

I've an array of array.

I'm trying this code to sort main array based of a field of every single element of the main array.

$field = $this->sorting;
usort($this->out_table["rows"], function($a, $b) use ($field) {
        return strnatcmp($a[$field], $b[$field]);
});

But I got this

 Parse error: syntax error, unexpected T_FUNCTION 

Referred to the second line, the one which starts with 'usort'

What am I missing?

My php version is

PHP 5.2.4-2ubuntu5.27 with Suhosin-Patch 0.9.6.2 (cli) (built: Mar 11 2013 14:14:48)
like image 820
realtebo Avatar asked Jan 09 '23 20:01

realtebo


1 Answers

PHP 5.2 doesn't support anonymous functions. Anonymous functions are instances of the Closure class, which as the docs say, wasn't introduced until 5.3... PS: _upgrade your PHP version, 5.2 was EOL'ed ages ago.

For now, though, you're best off writing your own class, pass the $field value to that class' instance and use the array-style callable argument:

class Sorter
{
    protected $field = null;
    public function __construct($field)
    {
        $this->field = $field;
    }
    public function sortCallback($a, $b)
    {
        return strnatcmp($a[$this->field], $b[$this->field]);
    }
}
$sorter = new Sorter($field);
usort($this->out_table["rows"], array($sorter, 'sortCallback'));

Which is basically what a Closure instance does, the anonymous function business is syntactic sugar in this case. The advantage of a class like this is that you could add some more sort-callbacks to it, and keep it handy as a sort of utility class with a sortAscending and sortDescending callback method, for example. Along with options you can set on the instance that make the sorter use strict (type and value) comparison where it's needed....

like image 159
Elias Van Ootegem Avatar answered Jan 15 '23 14:01

Elias Van Ootegem