0

I have an array like this one:

$a = array("MA1" => 0, "MA10" => 1, "MA20" => 2, "MA5" => 3, "SM10" => 4, "SM8" => 5, "SM20" => 6, "SN33" => 7);

I want to sort it, that I will have the following order:

$a = array("MA1" => 0, "MA5" => 3, "MA10" => 1, "MA20" => 2, "SM8" => 5, "SM10" => 4, "SM20" => 6, "SN33" => 7);

So I need a order which is alphabetical within the first two chars and numeric of the rest. So I think I have to do this with

uksort($a, "cmp");

So I need a function like this:

function cmp($a, $b) {
    // ???
    return strcasecmp($a, $b);
}

How do I need to write the function so that the order will be right?

Thank you in advance & Best Regards.

1 Answer 1

3

You can use built-in natural comparison function:

$a = array("MA1" => 0, "MA10" => 1, "MA20" => 2, "MA5" => 3, "SM10" => 4, "SM8" => 5, "SM20" => 6, "SN33" => 7);
uksort($a, "strnatcasecmp");
print_r($a);

The code above would produce following output:

Array
(
    [MA1] => 0
    [MA5] => 3
    [MA10] => 1
    [MA20] => 2
    [SM8] => 5
    [SM10] => 4
    [SM20] => 6
    [SN33] => 7
)
Sign up to request clarification or add additional context in comments.

Comments

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.