phparrayssortingnatural-sort

Naturally sort an array of alphanumeric strings


Im stuck on a sorting problem, I have an array with 10 numbers (1-10) and I need to sort the in the following way where 10 would come after 1, for example...

desired outcome

$arr['a1','a10','a2','a3','a4','a5','a6','a7','a8','a9'];

actual outcome

$arr['a1','a2','a3','a4','a5','a6','a7','a8','a9','a10'];

sort($arr);

$arr['a10','a1','a2','a3','a4','a5','a6','a7','a8','a9'];

I don't know the name of this type of sorting or how to perform it, if anyone could help me it would much appreciated.

NOTE: the numbers are part of a string


Solution

  • Try sort($arr,SORT_STRING) to explicitly treat the input as strings.

    EDIT: Now that you've given your actual strings, try this:

    usort($arr,function($a,$b) {
        $a = explode("=",$a);
        $b = explode("=",$b);
        return $a[0] == $b[0] ? strcmp($a[1],$b[1]) : strcmp($a[0],$b[0]);
    });