Damian Kęska
Damian Kęska

Reputation: 59

Sort long length numbers by value in PHP (parts of half-numeric strings)

I have some strings begining with numbers and currently PHP's default sort() is handling it diffirently than I expect.

Current sorting results:

111a
112a
1123a
204a
205a
20765a
3a

My expectations:

3a
111a
112a
204a
205a
1123a
20765a

Should I for example all elements with all elements extracting the number at first? How I could do that in PHP in easy way?

Upvotes: 0

Views: 61

Answers (1)

Tomasz Racia
Tomasz Racia

Reputation: 1806

Use another PHP function called natsort() ;)

So, in your case:

$temp = array(
    '111a',
    '112a',
    '1123a',
    '204a',
    '205a',
    '20765a',
    '3a',
);
natsort($temp);
var_dump($temp);

Upvotes: 5

Related Questions