mk_89
mk_89

Reputation: 2742

Naturally sort an array of alphanumeric strings

Im stuck on a sorting problem, I have an array with 10 numbers (1-10) and I need to sort the in the following way where 10 would come after 1, for example...

desired outcome

$arr['a1','a10','a2','a3','a4','a5','a6','a7','a8','a9'];

actual outcome

$arr['a1','a2','a3','a4','a5','a6','a7','a8','a9','a10'];

sort($arr);

$arr['a10','a1','a2','a3','a4','a5','a6','a7','a8','a9'];

I don't know the name of this type of sorting or how to perform it, if anyone could help me it would much appreciated.

NOTE: the numbers are part of a string

Upvotes: 1

Views: 297

Answers (3)

ToBe
ToBe

Reputation: 2681

You can change the behaviour of sort with it's second parameter.

Try this:

sort($arr, SORT_STRING);

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Try sort($arr,SORT_STRING) to explicitly treat the input as strings.

EDIT: Now that you've given your actual strings, try this:

usort($arr,function($a,$b) {
    $a = explode("=",$a);
    $b = explode("=",$b);
    return $a[0] == $b[0] ? strcmp($a[1],$b[1]) : strcmp($a[0],$b[0]);
});

Upvotes: 6

AJcodez
AJcodez

Reputation: 34156

Sure, you want to sort alphabetically, not numerically.

sort($arr, SORT_STRING);

ref: http://php.net/manual/en/function.sort.php

Upvotes: 0

Related Questions