PHP: Sort and Order Array Items / Elements / Numbers Naturally so 2 Comes before 10

by Yang Yang on June 3, 2009

in PHP Tips & Tutorials

By nature, a strict computer sorting algorithm would place ’10′ before ’2′. As a result of comparison on a byte by byte basis, the first byte of the 2 strings are determined in the order that 1 comes before 2, thus placing ’10′ before ’2′.

However, in a natural sorting algorithm, ’2′ comes before ’10′. In PHP, you can use the function natsort() instead of a traditional sort():

natsort($images);

Which would result in a reordered $images array with number digits in the filenames like this:

Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

Related Posts

{ 4 comments… read them below or add one }

Ron December 20, 2009 at 12:36 am

Thanks! It’s sorted a problem I have been having with my remote server (the local server was fine though!).

Reply

Ian May 16, 2010 at 9:45 am

Exactly what I was looking for. Thanks. One error though, you have nagsort in your code example.

Reply

De P July 30, 2010 at 11:54 pm

natsort or nagsort?

Reply

Yang Yang July 31, 2010 at 8:25 pm

Thanks. It’s now corrected as natsort().

Reply

Leave a Comment

Previous post:

Next post: