How to pass function name as an argument (usort)

In a blank app, I have defined a function called ‘cmp’ taking 2 parameters. I call this function like this: [SIZE=14px]
usort($fruits,“cmp”);
[/SIZE]

but it gives error:

 Error usort() expects parameter 2 to be a valid callback, function 'cmp' not found or invalid function name

This works fine in normal php outside of scriptcase.

How can I fix this?

(I’m simply trying to sort a multi-dimensional array by values in a key field. usort documentation is at http://php.net/manual/en/function.usort.php)

PHP 5.3 upwards allows anonymous functions so the function was inlined and it worked.

Currently in version 9.3 with PHP 7.2 does not work!


$array = array( 3, 2, 5, 6, 1 ) ;
usort( $array, "compare" ) ;
print_r( $array ) ;

function compare( $a, $b )
{
    if ($a == $b) return 0;
    if ($a < $b) return -1;
    return 1;
}

Any ideas?

maybe,
by directly integrating the function in usort, to deepen

$array = [3,2,1,5,6,7,4];
$val = usort($array, function ($a, $b){
echo "COMPARING: {$a} with {$b}
".’</br>’;
if ($a == $b)
{
return 0;
}
elseif ($a < $b)
{
return -1;
}
else
{
return 1;
}
});

then you can test with this
$array = [3,2,1,5,6,7,4];
$val = usort($array, function ($a, $b)
{
//echo "COMPARING: {$a} with {$b}
".’</br>’;
if ($a == $b)
{
return 0;
}
elseif ($a < $b)
{
return -1;
}
else
{
return 1;
}
}
);
var_dump($array);

or you can see whith:
echo $array[0].’</br>’;
echo $array[1].’</br>’;
echo $array[2].’</br>’;
echo $array[3].’</br>’;
echo $array[4].’</br>’;
echo $array[5].’</br>’;
echo $array[6].’</br>’;

array is sorted

Thanks for the reply.

Diogenes (SC support) suggested:

usort( $arreglo, array( $this, "comparar" ) );

and works!

Had the same situation, spent a lot of time for solving this problem. Yes, this:

usort( $myarr, array( $this, "cmp" ) );

is only the working solution. It is very intersting, why, but at least it is working now