Question

Why doesn't usort() sort the array?

if ( is_array( $tables ) ) {
    usort( $tables, 'sort' );
} else {
    echo "no array";
}

I always get this warning:

sort() expects parameter 1 to be array, string given

so php thinks its an array but usort() not

heres the sort function:

function sort( $a, $b ) {
    return strlen( $b ) - strlen( $a );
}
Was it helpful?

Solution

Note the error says sort() expects, not usort() expects. That's because PHP is interpreting the callback to usort as the built-in sort() method (which expects the 1st parameter to be an array), not your sort() method.

Try renaming your method to something else, like my_sort.

function my_sort( $a, $b ) {
    return strlen( $b ) - strlen( $a );
}

if ( is_array( $tables ) ) {
    usort( $tables, 'my_sort' );
} else {
    echo "no array";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top