phparrayssortingnatural-sortlexicographic-ordering

sort() puts alphanumeric string ending in 10 before another string ending in 2


I'm having trouble sorting an array in PHP and I'm having some trouble with the basic sort() routine.

For example,

$arr = array("J1", "N1", "J10", "J2");

When using the sort routine, my output is: J1, J10, J2, N1.

My desired output is: J1, J2, J10, N1.

Does anyone know a more suited sorting algorithm for this type of problem?


Solution

  • Look at the natsort function.

    $arr = array("J1", "N1", "J10", "J2");
    natsort($arr);
    
    var_dump($arr);
    
    array(4) {
      [0]=>
      string(2) "J1"
      [3]=>
      string(2) "J2"
      [2]=>
      string(3) "J10"
      [1]=>
      string(2) "N1"
    }