0

I am getting this result after performing the following on an array. Shouldn't this be sorting by 'computer_name'? You will see they are not alpha order.

usort($test, function($a, $b) {
    return $a['computer_name'] - $b['computer_name'];
});

echo "<pre>";
print_r($test);
echo "</pre>";


Array
(
    [0] => Array
        (
            [computer_id] => 367
            [account_id] => 1
            [computer_name] => EXAMPLE_ONE
            [last_username] => muah
            [timestamp] => 2014-01-01 17:06:04
        )

    [1] => Array
        (
            [computer_id] => 366
            [account_id] => 1
            [computer_name] => TESTING
            [last_username] => 
            [timestamp] => 2013-12-06 20:02:14
        )

    [2] => Array
        (
            [computer_id] => 365
            [account_id] => 1
            [computer_name] => JOE-SCHMOE
            [last_username] => 
            [timestamp] => 2013-12-06 20:02:03
        )

    [3] => Array
        (
            [computer_id] => 18
            [account_id] => 1
            [computer_name] => SPORT-ONE
            [last_username] => 
            [timestamp] => 2012-10-16 03:31:22
        )

    [4] => Array
        (
            [computer_id] => 3
            [account_id] => 1
            [computer_name] => SPORT-TWO
            [last_username] => 
            [timestamp] => 2011-03-03 03:35:46
        )

)

1 Answer 1

1

I think the issue is that EXAMPLE_ONE - TESTING, or EXAMPLE_ONE - SPORT-ONE is always equal to 0.

You could try using strcasecmp here, or the case insensitive version strcmp

Actually, looking at the documentation for usort, there's an example right in there. Your example above would be something like

usort($test, function($a, $b) {
    return strcmp($a['computer_name'], $b['computer_name']);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Good find... that did the trick! I just assumed, but when you explain as you did it makes perfect sense why the results were happening. Thanks!

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.