natsort

(PHP 4, PHP 5, PHP 7)

natsort — Sort an array using a "natural order" algorithm

Description

boolnatsort
( array&$array
)

This function implements a sort algorithm that orders alphanumeric strings
in the way a human being would while maintaining key/value associations.
This is described as a "natural ordering". An example of the difference
between this algorithm and the regular computer string sorting algorithms
(used in sort()) can be seen in the example below.

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

I got caught out through naive use of this feature - attempting to sort a list of image filenames from a digital camera, where the filenames are leading zero padded (e.g. DSCF0120.jpg) , will not sort correctly.Maybe the example could be modified to exhibit this behaviour (e.g. set array to -img0120.jpg','IMG0.png', 'img0012.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png)If the example hadn't used images I would have coded it correctly first time around!

This function can be very usefull, but in some cases, like if you want to sort a MySQL query result, it's important to keep in mind that MySQL as built'in sorting functions which are way faster than resorting the result using a complex php algorythm, especially with large arrays.

As noted in other notes, natsort() does _not_ always return the expected sort order. It seems especially buggy when decimals or 0 padding is used. I've filed this bug report on the issue:https://bugs.php.net/bug.php?id=74672

The last comment should have been posted in doc about (r)sort( ). Indeed, and unfortunately, ORDER BY *does not* perform natural ordering. So, sometimes we *must* do a SQL request followed by natsort( ).

// loop through the array foreach ($aryData as $aryRow) // set up the value in the array $arySort[$aryRow[$strIndex]] = $aryRow[$strSortBy];

// apply the natural sort natsort($arySort);

// if the sort type is descending if ($strSortType=="desc") // reverse the array arsort($arySort);

// loop through the sorted and original data foreach ($arySort as $arySortKey => $arySorted) foreach ($aryData as $aryOriginal) // if the key matches if ($aryOriginal[$strIndex]==$arySortKey) // add it to the output array array_push($aryResult, $aryOriginal);