0
function sort_searches($a, $b)
{
    return
    (
        (isset($b['Class_ID']) && !isset($a['Class_ID'])) 
        ||
        ($b['Results'] && !$a['Results']) 
        || 
        (is_array($a['Results']) && !$a['Results'] && !is_array($b['Results']))
    );
}

I'm using this function in usort(). The intended effect is that a list of searches will be sorted first by whether they have Class_IDs, and then second by results (with a non-empty array of results > results === false > results === empty array(). So a sorted set of searches would look like:

Class_ID with results
Class_ID with results === false
Class_ID with results === array()
No Class_ID with results
No Class_ID with results === false
No Class_ID with results === array()

Currently the functions sorts on results completely fine, but not on whether a search has a Class_ID.

usort($searches, 'sort_searches')

1 Answer 1

1

From the PHP docs:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Your function is not returning an integer.


To spell it out, let's say we wanted to write a sorting function for numbers (totally unnecessary, but for the exercise):

function sort_nums($a, $b)
{
    if ($a < $b) return -1; // $a is less than $b
    if ($a > $b) return 1; // $a is greater than $b
    return 0; // $a is equal to $b
}
Sign up to request clarification or add additional context in comments.

2 Comments

just reread your post. basically you're saying i need to return -1 when $a < $b, instead of 0?
Thanks, will try this and get back to you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.