Categories
PHP Tips & Tutorials

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

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
)

By Yang Yang

Hello, I'm Yang. I build online businesses that please people. Want to join in and post some useful articles on Kavoir.com? Shoot me a message.

6 replies on “PHP: Sort and Order Array Items / Elements / Numbers Naturally so 2 Comes before 10”

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

I would like to use this on an array of strings which all begin with a number. Specifically, I would like to sort the array returned by scandir()–the files are all named beginning with naturally ordered numbers. Is there a simple way to do this?

Comments are closed.