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
)

{ 4 comments… read them below or add one }
Thanks! It’s sorted a problem I have been having with my remote server (the local server was fine though!).
Exactly what I was looking for. Thanks. One error though, you have nagsort in your code example.
natsort or nagsort?
Thanks. It’s now corrected as natsort().