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
)

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

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

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

  3. 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.

Scroll to Top