PHP usort() expects parameter 2 to be a valid callback, not in a class
Asked Answered
S

3

9

I have a problem with usort not liking the second parameter (the sorting function). I have seen a lot of questions about this being a problem when in a class, and the answer for that is to pass an array of array($this, functionName) But in my case this is not working. The script is not a class, but I am getting this error:

PHP Warning:  usort() expects parameter 2 to be a valid callback, function 'cmp' not found or invalid function name in <filename.php>

So what is the problem with the second parameter, the function name, not being found? This is example code straight from the PHP website.

Specify answered 6/7, 2016 at 15:59 Comment(0)
S
12

If the code is not in a class, but you are using a namespace, usort expects the second parameter to have that namespace defined. But not in an array in similar style to using usort in a class.

This worked for me, where 'cmp' is the sorting function:

usort($arrayToSort, 'My\Full\Namespace\cmp');
Specify answered 6/7, 2016 at 15:59 Comment(1)
It's the Q&A format of posting. If you have a problem and come up with a solution, you can post in Q&A format.Specify
U
4

In case this helps, (&since this is top of Google), I had to do this

class MyObj{
        var $Supplier;
        function cmp($m, $n) {
            if ($m->Supplier == $n->Supplier) {
                return 0;
            }
            return ($m->Supplier < $n->Supplier) ? -1 : 1;
         }
 }
      
 usort($arrayToSort, array('My\Full\Namespace\MyObj', 'cmp'));
Umbrage answered 22/9, 2020 at 9:12 Comment(2)
Worked for me, even though my sort function was private.Bemoan
This worked for me as well - my function was private, so I only had to pass my class's namespace. This was for a Dokuwiki plugin, which I think is why I had to do it this way.Hopple
W
3

I put the callback function inside the function in which I put the usort() and it worked.

function callerFn() {

    if (!function_exists('callbackFn'))   {
        function callbackFn() {}
    }

    usort($arrayToSort, "callbackFn");

}

You can also do it as an unnamed function:

function callerFn() {

    usort($arrayToSort, function() {} );

}
Wera answered 31/12, 2019 at 20:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.